javascript 如何在jquery每个循环中的javascript中创建一个多维数组?

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

how to create a multi dimensional array in javascript inside a jquery each loop?

javascriptjqueryarraysmultidimensional-arrayeach

提问by Patrioticcow

I have this example:

我有这个例子:

var name;
var id;
var array = []; 

$.each(data, function(index, element) {
name = element.name;
id = element.id;
array[id] = name;
<a href="#" onClick="myFunction(array)">send</a>
console.log(array);
});

In this case .eachwill iterate 5 times and idwill become 1, 2, 3, 4, 5and namewill change to five names

在这种情况下.each将迭代 5 次,id并将变为1, 2, 3, 4, 5并且name将更改为五个名称

i would like to create a multidimensional array or an object that will look like this:

我想创建一个多维数组或一个如下所示的对象:

[1:name1] for the first iteration
[2:name2] for the second on
...

the pass each pair of values to the myFunctionfunction and inside that function to have access to the array values:

将每对值传递给myFunction函数并在该函数内部访问数组值:

function myFunction(array){ // alert the key and value }

function myFunction(array){ // 提醒键和值 }

Any ideas how can I accomplish this scenario?

任何想法我怎样才能完成这个场景?

回答by T.J. Crowder

It's not clear what you're trying to do, but if you want each entry in arrayto be an array containing the values of the id and name, you can change this line:

不清楚您要做什么,但如果您希望每个条目array都是一个包含 id 和 name 值的数组,您可以更改此行:

array[id] = name;

to

array[id] = new Array(id, name);

But I probably wouldn't use an array for that, I'd probably just use an object:

但我可能不会为此使用数组,我可能只使用一个对象:

array[id] = {id: id, name: name};

Then you can access it like this:

然后你可以像这样访问它:

x = array[id].name;

In fact, does arrayreally need to be an array at all? If not, just make it an object:

事实上,array真的需要一个数组吗?如果没有,只需将其设为对象:

data = {};

Make idthe key and namethe value:

制作id键和name值:

data[id] = name;

And this is how you loop it:

这就是你循环它的方式:

function myFunction(data) {
    var id, name;

    for (id in data) {
        name = data[id];
        alert("id is " + id + ", name is " + name);
    }
}

With a plain object like that, there's no need, but if the object you're looping may have a prototype behind it, you'd want to only look at the object's ownproperties:

对于像这样的普通对象,没有必要,但是如果您正在循环的对象后面可能有一个原型,您只想查看对象自己的属性:

function myFunction(data) {
    var id, name;

    for (id in data) {
        if (data.hasOwnProperty(id)) {
            name = data[id];
            alert("id is " + id + ", name is " + name);
        }
    }
}