javascript 将空数组作为数组键的值推送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7549816/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:30:47  来源:igfitidea点击:

push empty array as value of an array key

javascriptarrays

提问by itsme

I need to push a new array as the value of a parent array key.

我需要推送一个新数组作为父数组键的值。

this is my array.

这是我的阵列。

asd[
[hey],
[hi]

]

i would like to return.

我想回来。

asd[
[hey]=>[],
[hi]
]

i do:

我做:

var asd = new Array();
asd.push(hey);
asd.push(hi);
asd[hey].push(new Array());

so obviously is not ok my code 

回答by Hubro

Instead of new Array();you should just write []. You can create a nested array like this

而不是new Array();你应该只写[]. 您可以像这样创建嵌套数组

myarray =
[
    "hey",
    "hi",
    [
        "foo"
    ]
]

Remember that when you push things into an array, it's given a numerical index. Instead of asd[hey]write asd[0]since heywould have been inserted as the first item in the array.

请记住,当您将事物推入数组时,它会被赋予一个数字索引。而不是asd[hey]writeasd[0]因为hey将作为数组中的第一项插入。

回答by derp

You could do something like this:

你可以这样做:

function myArray(){this.push = function(key){ eval("this." + key + " = []");};}

//example
test = new myArray();

//create a few keys
test.push('hey');
test.push('hi');

//add a value to 'hey' key
test['hey'].push('hey value');

// => hey value
alert( test['hey'] );

Take notice that in this example testis not an arraybut a myArrayinstance.

请注意,在这个例子test中不是一个array而是一个myArray实例。



If you already have an array an want the values to keys:

如果您已经有一个数组并希望将值设置为键:

function transform(ary){
    result= []; 
    for(var i=0; i< ary.length; i++){result[ary[i]] = [];}
    return result;
}

//say you have this array
test = ['hey','hi'];

//convert every value on a key so you have 'ary[key] = []'
test = transform(test);

//now you can push whatever
test['hey'].push('hey value');

// => hey value
alert( test['hey'] );

In this case testremains an array.

在这种情况下test仍然是array.