javascript 在 jquery 每个循环中创建多维数组或对象

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

create multidimensional array or object in jquery each loop

javascriptjqueryarraysmultidimensional-array

提问by caramba

this is what I've got and been struggeling for hours. if I alert(i)in the each loop it gives me 1,2,3...but if I want to use as as key for a multidimensional array it is like a string "i"

这就是我所拥有的并且已经奋斗了几个小时。如果我alert(i)在每个循环中它给了我1,2,3...但是如果我想用作多维数组的键,它就像一个字符串"i"

$(document).ready(function(){
    var positions=[];

    $( ".box" ).each(function(i) {
        //alert(i);
        var elPositions = {};
        elPositions.i = $(this).offset().top;
        positions.push(elPositions);
        //$elPosArray[i] = $(this).offset().top;
        //$(this).html('outer height--> ' + $(this).outerHeight(true));
    });
    console.log(positions);
    //console.log(el);
});

There are Questions and answers to this topic but none of them helped me to get this to work.

这个主题有问题和答案,但没有一个能帮助我解决这个问题。

I would like to get an array or obj looking something like:

我想要一个数组或 obj 看起来像:

   positions[0]['offset'] = '120';
   positions[0]['height'] = '300';
   positions[1]['offset'] = '420';
   positions[1]['height'] = '180';
   positions[2]['offset'] = '600';
   positions[2]['height'] = '100';
   positions[3]['offset'] = '700';
   positions[3]['height'] = '300';

Here is a fiddle with the html http://jsfiddle.net/Z9WrG/

这是 html http://jsfiddle.net/Z9WrG/的小提琴

回答by Josh Harrison

You're pretty much there!

你几乎在那里!

In your loop, elPositions(here renamed data) is recreated new on each iteration, and then pushed into the array with a consecutive index. There's no need to specify iin the data object as iis assigned automatically when you push into the array.

在您的循环中,elPositions(此处重命名data)在每次迭代时重新创建新的,然后使用连续索引推送到数组中。当您推入数组时,无需i在数据对象i中指定自动分配的数据。

See updated fiddle: http://jsfiddle.net/Z9WrG/2/

查看更新的小提琴:http: //jsfiddle.net/Z9WrG/2/

and code:

和代码:

$(document).ready(function(){
    var positions=[];

    $( ".box" ).each(function() {
        var $this = $(this);
        var data = {};

        data.offset = $this.offset().top;
        data.height = $this.height();

        positions.push(data);
        // Now, positions[iteration_index] = { offset: x, height: y }
    });

    console.log(positions);
    console.log(positions[0].height);
    console.log(positions[0].offset);
});