带有自定义变量索引的 Javascript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16646690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript array with custom variable indexing
提问by Alan A
Is it possible to set the custom index of an array with a variable.
是否可以使用变量设置数组的自定义索引。
for example:
例如:
var indexID = 5;
var temp = {
indexID: new Array()
};
The above example sets the array index to indexID
and not 5
. I have tried using =
snd quotes but I without any success.
上面的示例将数组索引设置为indexID
和 not 5
。我曾尝试使用=
snd 引号,但没有任何成功。
Thnaks
纳克斯
回答by VisioN
Yes, just use square brackets notation:
是的,只需使用方括号表示法:
var temp = {};
temp[indexID] = [];
Also pay attention to the fact that temp
is an object, and not an array. In JavaScript all associative arrays(or dictionaries) are represented as objects.
还要注意它temp
是一个对象,而不是一个数组。在 JavaScript 中,所有关联数组(或字典)都表示为对象。
MORE:http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
更多:http : //www.jibbering.com/faq/faq_notes/square_brackets.html#vId
回答by Nick Fishman
I think what you want is:
我想你想要的是:
var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
回答by pvorb
With your code, you will create an object.
使用您的代码,您将创建一个对象。
Instead you can do
相反,你可以做
var indexID = 5;
var temp = [];
temp[indexID] = [];
回答by KooiInc
You are mixing Array
with Object
. Arrays know a (numeric) index, Objects consist of key-value pairs, where key may be any string.
您正在Array
与Object
. 数组知道一个(数字)索引,对象由键值对组成,其中键可以是任何字符串。
Not everyone would agree, bu you could extend Object.prototype
不是每个人都会同意,但你可以延长 Object.prototype
Object.prototype.append = function(key,val){
// confine to Object instances
if (this.constructor !== Object &&
!/object/i.test(this.constructor.prototype)) { return this; }
this[key] = val;
return this;
}
And subsequently use:
随后使用:
var temp = {}.append(indexID,[]};
回答by ALI ALRIKABI
for node-red project i had to add Apostrophe to the index name
对于节点红色项目,我必须在索引名称中添加撇号
var Trend_1={};
Trend_1[**'x'**]=Date_TimeArray;
回答by nihal malik
var index=7; //YOUR CUSTOM INDEX
var newarray=[];
If you need array index to be an array you can do it like this:
如果你需要数组索引是一个数组,你可以这样做:
newarray[index] = {
'KEY':'VAL',
'KEY':'VAL',
'KEY':'VAL'
}
If you need to assign just a value to your custom array index you can do it like this:
如果您只需要为自定义数组索引分配一个值,您可以这样做:
newarray[index] = "ANY-THING-YOU-WANT"