user1915539
user1915539

Reputation: 11

accessing elements in a list in javascript html

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.

Upvotes: 1

Views: 1233

Answers (2)

tom
tom

Reputation: 19153

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 ...
}

Upvotes: 4

Igor Raush
Igor Raush

Reputation: 15240

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.

Upvotes: 1

Related Questions