Skip to content
Advertisements

Array entries()

“entries()”method returns a new Array Iterator object. The object contains the entries for each item in the Array, and can be advanced with next():

        let arr = ['true', 'codes', '.org'];
        let x = arr.entries();
        console.log(x.next().value); // arr[0]
        console.log(x.next().value); // arr[1]
        console.log(x.next().value); // arr[2]

output:

0, “true”
1, “codes”
2, “.org”


For example, we have a list of names. We need to correct them by placing numbers in front of them. We can use it for that.

        let names = ['john', 'alice', 'barrry' , "oliver","rick"];
        let line = names.entries();
        console.log(line.next().value); // names[0]
        console.log(line.next().value); // names[1]
        console.log(line.next().value); // names[2]
        console.log(line.next().value); // names[3]
        console.log(line.next().value); // names[4]

output:

[0, “john”]
[1, “alice”]
[2, “barrry”]
[3, “oliver”]
[4, “rick”]


can be written in a shorter way using the “for loop”.

        let names = ['john', 'alice', 'barrry' , "oliver","rick"];
        let line = names.entries();
        for (var i = 0; i < names.length; i++) {
            console.log(line.next().value)
        }
Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: