javascript 将元素添加到jquery中的二维数组

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

Add elements to 2D array in jquery

javascriptjquery

提问by Erma Isabel

Possible Duplicate:
How to create a two dimensional array in JavaScript?

可能的重复:
如何在 JavaScript 中创建二维数组?

I want to push elements to 2D array,

我想将元素推送到二维数组,

My code is,

我的代码是,

        var results = [];
        var resultstemp = [];
        function bindlinks(aamt,id1) {
        resultstemp=results;        
            imagesArray.push($("#image1").mapster("get"));

            if(results.length==0)
            {
            results.push([id1]);    
            }
            else
            {
               var ck=0;
               var lng=results.length;
                for (var i = 0; i < lng; i++) {

                  if(results[i]==id1)
                  {

                    ck=1;
                     results = jQuery.grep(results, function(value) {
                        return value != id1;
                      });

                  }                                     
                }                   
                if(ck==0)
                {
                results.push(id1);                  
                }                   
            }

I want to push idas well as aamtto array. Here i am pushing only id to array. I am not sure about how to add aamtto second position in 2D array.

我想推动id以及aamt阵列。在这里,我只将 id 推送到数组。我不确定如何添加aamt到二维数组中的第二个位置。

Help me please,

请帮帮我,

Thank you

谢谢

回答by Xmindz

Change the declaration as follows:

更改声明如下:

var results = new Array();

and change the pushas follows:

并更改push如下:

results.push([id1,aamt]);

Hope it would help

希望它会有所帮助

回答by Endre Simo

The logic behind the method to push two separate values in the same array evenly is something like this:

在同一数组中均匀推送两个单独值的方法背后的逻辑是这样的:

var array = [];
function push(id1, aamt) {
    for (var i= 0; i < 10; i++) {
        if (i%2 == 0) {
            array.push(id1);
        }
        else {
            array.push(aamt);
        }
    }    
}

push(10, 12);
console.log(array); // 10, 12, 10, 12.....

Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.

注意我对代码进行了相当多的抽象,因为对我来说代码应该做什么不是很明显,但原理很简单:使用模(%)运算符来测试值是奇数还是偶数。如果奇数添加第一个值,如果偶数添加第二个值。

Hope it helps.

希望能帮助到你。