Javascript for loop syntax

As javascript developers, we all have to write a lot for loops. A couple of months later I saw an alternative syntax that I really liked. However, I am now wondering if there is another good way.

Let's say that I have an array of data representing users in the system. I have done this before:

var users = [
    { name: "A"},
    { name: "B"},
    { name: "C"},
    { name: "D"},
    { name: "E"}
];

var numOfUsers = users.length;
for(var i=0; i<numOfUsers; i++) {
    var user = users[i];
    // ...
}

There is another line var user = users[i];. Usually I feel more comfortable if I have userinstead users[i]. So the new way:

for(var i=0; user=users[i]; i++) {
    // ...
}

I am also wondering if the second approach creates problems in some browsers. One of my colleagues reported that this syntax is a bit erroneous in IE.

: , . , . - :

for(var i=0; typeof (user=users[i]) !== "undefined"; i++) {
   // ...
}

. , , , 100% , ( :)).

+4
4

"" numOfUsers.

: users[i], true ( user undefined, false ), , true, "false-y" - .

+6

:

for(var i=0; user=users[i]; i++) {
    // ...
}

... , , user "" (0, "", null, undefined, NaN , , false), . , , , , .

for , : for, . (JavaScript var , ; ES6 let, .)

JavaScript- ( ES5) , , :

users.forEach(function(user) {
    // ...
});

..., i numUsers user ( ). , . , .

+2

, , true , , false, . , for, JavaScript - , , var ( i). , . , - , .

0

jQuery, jQuery.each .

In any case, you can look at the source code of this function and copy the corresponding parts for your own function foreach: http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.each

0
source

All Articles