0

I have this:

var one = ['12','24','36'];

var two = ['10','20','30'];

If I do:

alert(one) I have: 12,24,36. And it's ok.

I need to have the name of the array from another function, where I call it from a for like this:

var test = [one,two]

for (i = 0; i < test.length; i++) {
  alert(test[i]);
}

I have "12,24,36" and then "10,20,30" in the alert, but I need the name of the array, not the content. How to do?

I want two alert with: "one" and "two", the name of Array.

5
  • 2
    You can create an array with the name in it and (in an other array) the numbers. ["one", [1, 2, 3, 4]] Commented Sep 24, 2015 at 11:05
  • 2
    What you're trying to do? There could be better way Commented Sep 24, 2015 at 11:05
  • Make a new variable where you can hold a string since you want the name? Commented Sep 24, 2015 at 11:06
  • @Matthijs, I can't create that array. Or maybe I don't understand what you mean. Commented Sep 24, 2015 at 11:06
  • Why not use object literal instead and just use the key as the name and the value as an array ? Commented Sep 24, 2015 at 11:10

4 Answers 4

3

Use an object to hold your arrays:

var obj = {
    one: ['12','24','36'],
    two: ['10','20','30']
}

for (var p in obj) {
  console.log(p); // log the key
}

Alternatively you can use Object.keys(obj) to retrieve an array of the object keys.

And if you need to log the array contents:

for (var p in obj) {
  console.log(obj[p]); // log the array contents
}

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, I agree with elad.chen. You can try something like:

var objects = [
    {name:"one",value:['12','24','36']},
    {name:"two",value:['12','24','36']}
];

for(var i=0;i<objects.length;i++){
    console.log(objects[i].name); 
    console.log(objects[i].value); 
}

Comments

0

You can use an "Object Literal" and use the property name as the name, and the value as the array..

For example:

var arrays = {
"one": [1,2,3],
"two": [1,2,3]
}

for ( var k in arrays ) {
  alert('"Array name" = ' + k)
  alert('"Array value" = ' + arrays[k].toString() )
}

Comments

0

At some place, the name must be set. While Javascript is can add properties to objects, this can be used for a name property without changing the behaviour of the arrays.

var one = ['12', '24', '36'];
one.name = 'one';
var two = ['10', '20', '30'];
two.name = 'two';
var test = [one, two], i;

for (i in test) {
    document.write(test[i].name + '<br>');
}

Comments

Your Answer

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