JavaScript对象维度



我想定义一个二维对象,但是没有成功。

var b = [1,2,3,4,5,6,7,8];
var a = {};
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
    for(s=0;s<4;s++){
       a[c[s]]=b[s];        
    }   
}
document.writeln(JSON.stringify(a));
输出:

{"baslik":1,"resim":2,"icerik":3,"links":4}

我想要这个输出:

{"baslik":1,"resim":2,"icerik":3,"links":4},  
{"baslik":5,"resim":6,"icerik":7,"links":8}

尝试:

var a = []; //Must be a array
var b = [1,2,3,4,5,6,7,8];
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
    var obj = {} //Object
    for(s=0;s<4;s++){
        obj[c[s]]=b[s+4*i];       
    }
    a.push(obj)
}
document.writeln(JSON.stringify(a));

试一下

var b = [1,2,3,4,5,6,7,8];
var a = [];
var c = ["baslik","resim","icerik","links"];
var n= Math.floor(b.length/c.length);
var k=0;
for(var i=0;i<n;i++){
  
  var entity={};
  for(var j=0;j<c.length;j++){
    entity[c[j]]= k<b.length ? b[k++] : 0;
  }
  a.push(entity);
}
console.log(JSON.stringify(a));

尝试:

var b = [1, 2, 3, 4, 5, 6, 7, 8];
var a = [];
var c = ["baslik", "resim", "icerik", "links"];
var n = c.length;
b.reduce(function(x, num, i) {
  x[c[i % n]] = num;
  if (((i + 1) % n) == 0) {
    a.push(x);
    x = {};
  }
  if ((i + 1) == b.length) return a;
  return x;
}, {})
console.log(JSON.stringify(a));

相关内容

  • 没有找到相关文章

最新更新