简体   繁体   中英

What is the meaning of a for/in loop on a string?

Is this code even valid JavaScript?

for (item in "abc") {  
    console.log(item);  
}  

Output:

0  
1  
2  

What is the meaning of a for/in loop on a string?

If you think of a string as an array of characters, the purpose of looping over a string would be to iterate through each of the characters.

In JavaScript for..in loops will return the keys in an object or array, so what you're seeing are the array indices. A more useful format would be:

var str,
    item;
str = "abc";
for (item in str) {
    console.log(str[item]);
}

Which will output 'a' , 'b' , and 'c' .

Is this code even valid JavaScript?

It is now, but there were issues in the past.

Note that for older browsers, array indices weren't supported on strings, so a backwards compatible way to iterate over the characters in a string is:

var str,
    i;
str = "abc";
for (i = 0; i < str.length; i++) {
    console.log(str.charAt(i));
}

It is.

What you see is the index / name of property in the string. Indexing the string like "abc"[0] results in a .

You may index an object with the property name too.

var x = {
  foo: "hi"
};
console.log(x["foo"]);

The loop just goes through all members of the object.

It is basically a foreach loop that goes through each item. In this case the string "abc" It looks like it is just printing out string position but this can be used with objects to iterate through them.

That is valid code. A for in loop in JavaScript will iterate through the set of keys in an object. In the case of "abc" the keys include the index of each character, as well as any additional properties added to the String prototype.

As a result of for in finding these prototype properties (especially if object has been modified) it is usually suggested to use a mechanism to skip them. In this case, you could use

if(!"abc".hasOwnProperty(item))continue;

If you were to use the index, named item here, you could access the characters individually as seen below

 for (item in "abc") { console.log(item); //this will log the letters one at a time console.log("abc"[item]); } 

for/in iterates the enumerable properties of an object.

Because JS allows you to read the characters of a string using array syntax as in str[1] , it exposes a numeric property for each index into the string and that is what your 0, 1, 2 output is from. Those are the enumerable properties of the string object.

It is logging the indexes of letters in the string.

This outputs the letters:

string = "abc"; for(var i = 0; i < string.length; i++){ console.log(string[i]); } string = "abc"; for(var i = 0; i < string.length; i++){ console.log(string[i]); } Outputs:

    a
    b
    c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM