0

I took time to read about accessing properties of objects, but could not find out a way to solve my problems.

  1. Let us say I have 10 arrays, of name arr1, arr2, arr3 ... arr10. How would i access the length of all the arrays without using the eval()? I did it with a for loop, and eval("arr" + i + ".length"). I know arr1["length"] works, but how to access the length of all the arrays? using a loop?
  2. How would I access functions like split(), splice() or pop() ... of all this arrays?
  3. Let us say arr1 = ["tab1", "tab2"], where tab1, tab2 are defined later as arrays. If I wish to access the length of tab1 from arr1 how should I do? And if i also want to access the defined functions on arrays?
franckstifler
  • 396
  • 2
  • 11

3 Answers3

0

You should move all these arrays to a parent object or array.

Also you should not avoid eval. Refer Why is using the JavaScript eval function a bad idea?

var arr1 = [1,2];
var arr2 = [1,2,3,4];
var arr3 = [1,2,3];
var arr4 = [1,2,6,4,3,6,];
var arr5 = [1];

var obj = {
  array1: arr1,
  array2: arr2,
  array3: arr3,
  array4: arr4,
  array5: arr5
}

Object.keys(obj).forEach(function(o){
  document.write(obj[o].length + "<br/>");
});
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Let us say I have 10 arrays, of name arr1, arr2, arr3 ... arr10. How would i access the length of all the arrays without using the eval()? I did it with a for loop, and eval("arr" + i + ".length"). I know arr1["length"] works, but how to access the length of all the arrays? using a loop?

If these arrays are defined as following inside a function

var arr1 = [];
var arr2 = [];

Then you can't access them by name.

You need to define the array inside an object. for example

var obj = {
  "arr1" : [1,2],
  "arr2" : [2,3]
}

If know the array name, you can access the array by doing

console.log(obj.arr1);

or

console.log(obj["arr" + 1 ]); //1 can be replaced by iterating i

However, if these arrays are defined in global context (outside any function), then you can access them via window object.

window["arr1"]

Let us say arr1 = ["tab1", "tab2"], where tab1, tab2 are defined later as arrays. If I wish to access the length of tab1 from arr1 how should I do? And if i also want to access the defined functions on arrays?

If tab1 are defined as 'var tab1 = [];' then you can't access this through name.

You need to wrap those arrays inside an object again.

var obj = {"tab1" : []};

Then you can access it by doing

console.log(obj[arr1[0]]);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

If you don't know the number of arrays in advance, an array of arrays works fine too:

var arrays = [[1,2], [1,2,3,4], [1,2,3], [1,2,6,4,3,6,], [1]];

for (var i = 0; i < arrays.length; i++) {
    console.log(arrays[i].length);
    document.write('<p>[' + arrays[i] + '].length = ' + arrays[i].length + '</p>');
}
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402