variable as index in an associative array - Javasc

2019-03-12 00:33发布

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:

var arrayName = new Array;

arrayName["indexName"] = value;

// i know i can also do the last line like this:

arrayName.indexName = value;

When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:

arrayName[eval("nume")] = value;

Where:

var var1 = "index";
var var2 = "Name";

var nume = '"' + var1 + var2 + '"'; 

but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"

Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?

7条回答
够拽才男人
2楼-- · 2019-03-12 01:09

Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?

And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';

查看更多
登录 后发表回答