变量作为关联数组中的索引 - Javascript [英] variable as index in an associative array - Javascript
问题描述
我正在尝试创建一个关联数组,创建一个空数组,然后添加一个( indexName
- > value)对:
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;
当我将值分配给 indexName
我希望 indexName
是动态的和变量的值。所以我尝试了这个:
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;
其中:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
但是: alert(arrayName [indexName]);
没有返回值...它说未定义
but: alert(arrayName["indexName"]);
doesn't return "value"... it says "undefined"
我有什么遗漏吗? (我不熟悉 eval()
);如果我正在尝试的方式是死胡同,还有另一种方法可以使关联数组的索引名称值动态吗?
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?
推荐答案
起初我认为你不需要一个真正的数组对象来做你需要的东西,你可以使用一个普通的对象。
At first I don't think you need a real array object to do what you need, you can use a plain object.
你可以简单地使用括号使用变量值访问属性的表示法:
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
数组只是对象,关联数组的概念可以通过使用简单对象来实现,对象是包含值的属性的集合。
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
当你需要存储数字索引时,真正的数组很有用,它们会自动更新它们的长度分配索引时,code>属性,或者
推送
一个值。
True arrays are useful when you need to store numeric indexes, they automatically update their length
property when you assign an index or you push
a value to it.
这篇关于变量作为关联数组中的索引 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!