1

I have a list - [getFamilyPkg, getActivePkg, getEligiblePkg, getActivePkgForDeactivation], want to get each element in this list in a javascript function.
How to do it? Thanks in advance.

0

2 Answers 2

4

Assume list is stored in a variable called arr.

for (var i = 0; i < arr.length; i++) {
  var elem = arr[i];
  // elem is either getFamilyPkg, or getActivePkg, or ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

for (var i=0;i<3;i++) { webService_list.remove(0); } Why this won't work?
There is no remove method on JS arrays. Use pop instead.
1

Tommy's answer is actually incorrect. for (var i in arr) loops over all attributes/properties of the arr object prototype, which includes builtin functions like slice(), etc. See jsfiddle example here: http://jsfiddle.net/sEtMw/ (check the console and you will see a bunch of extra properties other than the array elements.

There are a few approaches (once again assuming the array is named arr):

var elem;
for (var i = 0, len = arr.length; i < len; i++) {
    elem = arr[i];
    // elem is actually one of the array elements here
}

Another option is as follows:

var elem;
while (elem = arr.shift()) {
    // elem is one of the array elements
}

Please note that the second approach does not keep the array intact. i.e. at the end of the loop, the array will be empty. But if you are okay with that, the syntax is definitely cleaner. Both approaches are illustrated here: http://jsfiddle.net/z7zKK/. The variable arr is logged at the end to illustrate that it is empty.

4 Comments

Yes, you are right. Let me edit my answer to use a simple i = 0...i++ approach. You get a big upvote from me!
In your defense, I think the fact that javascript lacks a foreach loop is a terrible terrible flaw!
Yea, it's pretty bad. Luckily underscore.js comes with a _.each(...)!
Yeah, and jQuery as well, but while I cannot speak for _.each efficiency, jQuery.each is roughly 20 times slower than a for loop in similar situations. I have no clue how they wrote it to be so slow. Potentially jQuery object creation overhead?

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.