简体   繁体   中英

for in loop behaving strangely in javascript

var friends=['2','3'];
console.log(friends);
var rooms=[];
for(var friend in friends){
var room = 'userid'+friend+'friends';
console.log(room);
rooms.push(room);
}
console.log(rooms);    

this outputs

[ '2', '3' ]
 userid0friends
 userid1friends
 [ 'userid0friends', 'userid1friends' ]

3 is neglected entirely, and it behaves even more strangely on my node.js server

friend here is the index of your array, not the value at the index

var room = 'userid'+friends[friend]+'friends';

Plus when looping through an array I don't recommend to use for..in loops, you can use Array.prototype.map or plain for loop with the length of your array

Array map example:

var friends=['2','3'];
console.log(friends);
var rooms= friends.map(function (friend, index) {
    return 'userid' + friend + 'friends';
});
console.log(rooms);

Plain for loop:

var friends=['2','3'];
console.log(friends);
var rooms=[];
for (var i = 0, l = friends.length; i < l; ++i) {
    var room = 'userid' + friends[i] + 'friends';
    console.log(room);
    rooms.push(room);
}
console.log(rooms);

The for in structure is used to loop the object, for key in object , key is the property name of the object, when used for an array, key will be the array index.

You could use .map to get your result:

var friends=['2','3'];

var rooms = friends.map(function(e) {
  return 'userid'+e+'friends';
});

A for in loop is used to enumerate objects. You are trying to iterate over an array. A better technique for iterating would be a regular for loop or the Array.forEach() method.

In a for in loop, the variable contains the key, not the value. To get the value, use the key:

for(var i in friends){
    var friend = friends[i];
    ...
}

But, again, this enumerates an object, including any properties besides the array elements. This means that if any code adds a method to Array.prototype , that method will also be enumerated. Using .forEach() is better:

friends.forEach(function (friend, i) {
    ...
});

Better yet, since you are trying to create a new Array based on the contents of another, use Array.map() . That is exactly what it's for.

var rooms = friends.map(function (friend, i) {
    return 'userid'+friend+'friends';
});

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