简体   繁体   中英

Javascript for loop syntax

As javascript developers we all have to write a lot of for loops. Before a couple of months I saw an alternative syntax, which I really liked. However, I'm now interested, is there any other nice way.

Let's say that I have an array of data representing users in a system. What I did before is:

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 one additional row var user = users[i]; . Normally I feel more comfortable if I have user instead of users[i] . So, the new way:

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

I'm also wondering if the second approach produces problems in some of the browsers. One of my colleagues reported that this syntax is a little bit buggy under IE.

Edit: Thankfully, the answers below pointed me out to the right direction. If some of the elements of the array is falsy then the loop will stop. There is some kind of solution:

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

But that's too much for me. So, I guess that I'll use this syntax only when I'm 100% sure that all the elements are truly (which means never :)).

In your “new” approach, you don't need numOfUsers any more.

As for the potential problems: This approach relies on all users[i] having values evaluating to true for the loop to continue (and user becoming undefined , equal to false and therefor ending the loop after the last user is processed) – but sometimes you might have data where not every record evaluates to true , but “false-y” values might also occur in the data – and in that case, this approach of course fails.

The problem with this approach:

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

...is that it assumes user won't be "falsey" ( 0 , "" , null , undefined , NaN , or of course false ) until you've gone past the end of the array. So it'll work well with an array of non-null object references, but if you then get in the habit of using it, it will bite you when you have an array of numbers, or strings, or such.

The other reason not to declare variables within the for construct is that it's misleading: Those variables are not scoped to the for loop, they're function-wide. (JavaScript's var doesn't have block scope, only function or global scope; ES6 will get let which will have block scope.)

On modern JavaScript engines (or with an "ES5 shim"), you can of course do this:

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

...which has the advantage of brevity and not having to declare i or numUsers or even user (since it's an argument to the iteration callback, and nicely scoped to that). If you're worried about the runtime cost of doing a function call for each entry, don't be . It'll be washed out by whatever actual work you're doing in the function.

I'm amazed if the second syntax works at all your middle operation should evaluate to true for each loop you want to complete and false as soon as you want to be done looping. As for any issues with your first for loop, a JavaScript is function scoped so that inner var statement will still leak to the containing function (as well as that i ). This is different than most other languages that have block scoping. It's not so much of a problem but something to keep in mind if you are debugging.

If you are already using jQuery, you can use the jQuery.each function to loop over your arrays.

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

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