0
for i in [name, matches_total, matches_won, matches_lost]:
    doSomething(i)

I tried doing this for JS but it did not work. Basically, I want it to do whatever it has to do over each of the variables. How do I do this with JS?

My attempt:

for (i in [name, matches_total, matches_won, matches_lost]){
    doSomething(i);
}

3 Answers 3

3

JavaScript doesn't have quite the same in operator. If you are in an environment that supports forEach, it's relatively close in style (except that you define an inner anonymous function for the loop, a bit like a Python lambda:

[name, matches_total, matches_won, matches_lost].forEach(function(i) {
    doSomething(i);
});

In this case (a case where you're calling a single function on each list item) you can simplify this in a way I find quite nice syntactically:

[name, matches_total, matches_won, matches_lost].forEach(doSomething);
Sign up to request clarification or add additional context in comments.

Comments

1
for (var i = 0; i < list.length; ++i) {
    doSomething(list[i]);
}

There are two kinds of for loops, the for-in loop designed for objects, and a three-statement for loop for (;;). Using for-in on an array is not recommended, as it traverses its prototype chain as well.

5 Comments

@Zoidberg'-- In what way is it fixed?
i is index, not the element itself. Also the for loop itself was wrong.
@David: Zoidberg fixed the index vs. element issue. You fixed the off-by-one in his solution
@Zoidberg'-- Wrong. i was not the index but the last element in the array. I was traversing the array backwards. And your subsequent edit was wrong.
@David I was talking about your initial answer. I think we both edited it at the same time. I didn't notice the --, my bad. Sorry.
0
var my_array = [name, matches_total, matches_won, matches_lost]

for (var i in my_array){
    doSomething(my_array[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.