循环嵌套数组并使用值渲染div

时间:2018-01-11 08:27:24

标签: javascript jquery html arrays loops

我有一个看起来像这样的数组:

arr = [
  ["10", "1", "1200", "630"],
  ["272", "45", "654", "654"],
  ["10", "139", "367", "372"],
  ["825", "134", "369", "371"]
];

每个数组内部的值都是我要渲染的div的参数(x,y,width,height)。所以例如第一个div应该有道具:

left: 10,
top: 1,
width: 1200,
height: 630

我目前的实现如下:

for (var i = 0; i < arr.length; i++) {
      $('<div/>', {
          class: 'class-' + i
        }).appendTo($('body'));
      for (var j = 0; j < arr[i].length; j++) {
            $('.class-' + i).css({
                position: 'absolute',
                left: arr[i][j],
                top: arr[i][j],
                width: arr[i][j],
                height: arr[i][j]
         });
     }
}

所以在这种情况下,我想为每个数组创建4个不同的div,并在每个数组中给出适当的CSS样式。 不幸的是它没有用,因为我在索引方面遇到了一些问题。

你知道如何解决这个问题吗?

谢谢!

6 个答案:

答案 0 :(得分:3)

问题在于这部分代码:

for (var j = 0; j < arr[i].length; j++) {
        $('.class-' + i).css({
            position: 'absolute',
            left: arr[i][j],
            top: arr[i][j],
            width: arr[i][j],
            height: arr[i][j]
        });
}

您必须仅为设置一次设置样式。在您的代码中,对于div class-i,其中i= 1 to arr.length,每个arr = [ ["10px", "1px", "12", "63"], ["272px", "45px", "65", "65"], ["101px", "139px", "36", "37"], ["825px", "134px", "36", "31"] ]; for (var i = 0; i < arr.length; i++) { $('<div/>', { class: 'class-' + i }).appendTo($('body')); $('.class-' + i).css({ position: 'absolute', left: arr[i][0], top: arr[i][1], width: arr[i][2], height: arr[i][3] }); }设置 css 样式4次。

div{
  background-color:red;
  border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SUBSYSTEM=="usb", ATTR{idVendor}=="[yourdevicevendor]", MODE="0664", GROUP="plugdev"

答案 1 :(得分:2)

You can use .map(), pass an object to .css(). Note also, left and top values should have "px" concatenated to the numeric value

arr = [
  ["10px", "1px", "1200", "630"],
  ["272px", "45px", "654", "654"],
  ["10px", "139px", "367", "372"],
  ["825px", "134px", "369", "371"]
];
$("body")
  .append(
    arr.map(([left, top, width, height], i) =>
      $("<div>", {
        "class": "class-" + i,
        text: i,
        css: {left, top, width, height}
      }))
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

plnkr http://plnkr.co/edit/4DgX13CoQAy9QC8oUA1T?p=preview

答案 2 :(得分:1)

你不想再次迭代它。在您的第一个for循环中,您获得["10", "1", "1200", "630"]。如果再次遍历它,则会获得单个值。这就是你要找的东西 - 我对jQuery有点生疏,你可以优化它。

for (var i = 0; i < arr.length; i++) {
    var parent =  $('<div/>', {
        class: 'class-' + i
    }).appendTo($('body'));
    $('.class-' + i).css({
        position: 'absolute',
        left: arr[i][0],
        top: arr[i][1],
        width: arr[i][2],
        height: arr[i][3]
    });
}

答案 3 :(得分:1)

这是你的fiddle。希望有所帮助。

k = 6
a = np.zeros((4, 4, 4))
pos = np.random.randint(0, 4, size=(k, a.ndim))
a[pos[:, 0], pos[:, 1], pos[:, 2]] = 1
var arr = [
       ["10", "1", "1200", "630"],
       ["272", "45", "654", "654"],
       ["10", "139", "367", "372"],
       ["825", "134", "369", "371"]
     ];
     
 arr.forEach(function(a) {
 	var div = $('<div/>').css({
    left: a[0],
    top: a[1],
    width:a[2],
    height: a[3]
  });
 	$('body').append(div);
 });

答案 4 :(得分:0)

&#13;
&#13;
for (var i = 0; i < arr.length; i++) {
  $('<div/>', {
    class: 'class-' + i
  }).appendTo($('body'));
  $('.class-' + i).css({
    position: 'absolute',
    left: arr[i][0],
    top: arr[i][1],
    width: arr[i][2],
    height: arr[i][3]
  });

}
&#13;
&#13;
&#13;

你只需要一个循环。

答案 5 :(得分:0)

以下是使用reduce和recursive函数的示例:

&#13;
&#13;
var arr = [
  ["10px", "1px", "1200", "630"],
  ["272px", "45px", "654", "654"],
  ["10px", "139px", "367", "372"],
  ["825px", "134px", "369", "371"]
];
var mapValuesToCss = ([left, top, width, height])=>
  Object.assign(
    {left,top}
    ,{
      width:width+"px",
      height:height+"px"
    }
  );
var addIndexAsContent = (value,index)=>value.html(index)
var createDivsReduce = css =>
  css.reduce(
    (divs,css)=>
      divs.concat(
        $(
          "<div>",
          css
        )
      )
    ,[]
  );
var createDivsRecursive = divs => css => {
  if(css.length===0){
    return divs;
  }
  return createDivsRecursive
    (divs.concat($("<div>",css[0])))
    (css.slice(1));//recursively call itself
}
//using reduce
$("body")
  .append(
    createDivsReduce(arr.map(mapValuesToCss))
    .map(addIndexAsContent)
  );
//recursively
$("body")
  .append(
    createDivsRecursive([])(arr.map(mapValuesToCss))
    .map(addIndexAsContent)
  );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;