JavaScript(JS) array method - keys
The keys()
method is an array method in JavaScript that returns an array iterator object with the keys of an array. The keys are the index numbers of the elements in the array.
Here's the syntax of the keys()
method:
array.keys();
array
is the array that thekeys()
method is called on.
The keys()
method returns an iterator object that contains the keys of the array.
Here's an example of how to use the keys()
method:
let array = ['apple', 'banana', 'orange']; let iterator = array.keys(); console.log(iterator.next()); // { value: 0, done: false } console.log(iterator.next()); // { value: 1, done: false } console.log(iterator.next()); // { value: 2, done: false } console.log(iterator.next()); // { value: undefined, done: true }
In this example, we have an array array
containing the elements ['apple', 'banana', 'orange']
. We use the keys()
method to get an iterator object containing the keys of the array. We then use the next()
method of the iterator object to iterate over the keys of the array. The output of this code will be:
{ value: 0, done: false } { value: 1, done: false } { value: 2, done: false } { value: undefined, done: true }
Note that the keys()
method was introduced in ECMAScript 6, so it may not be supported by older browsers. If you need to achieve the same functionality in older browsers, you can use a for
loop to iterate over the keys of the array:
let array = ['apple', 'banana', 'orange']; for (let i = 0; i < array.length; i++) { console.log(i); }
This code uses a for
loop to iterate over the keys of the array. It prints the index numbers of the elements in the array to the console. The output of this code will be:
0 1 2