JavaScript Array keys() MethodThe keys() method creates and returns a new iterator object which holds the key for every index in the array. This method does not affect the original array. SyntaxParameterIt does not hold any parameter. ReturnIt returns a new array iterator object. JavaScript Array keys() ExampleLet's see some examples to understand better. Example1 Here's the simple implementation of keys() method in array. Test it NowOutput: So, according to the number of elements present in the array, a key is assigned to each one. Example2 Implementing keys() method with holes in between the array. Test it NowOutput: Note: It is clear from the above example that Array keys() method does not ignore the holes present as an array element in the given array. It assigns a key value to that empty hole too. Also, the keys are assigned in an increasing order sequence to each element.Example3 Test it NowOutput: Example4 Here's an example to generate keys for a user-define array. Test it NowOutput: Initially, the user will input the elements through prompt box which will be displayed as: After clicking on Get Keys button, the keys will be generated as: Thus, keys() method is a direct approach forgenerating keys for the array values.
Next TopicJavaScript Array
|