Javascript中的嵌套多维数组

时间:2016-06-17 09:52:42

标签: javascript

鉴于此代码:

    private static bool IsBOMWhitespace(char c)
    {
#if FEATURE_LEGACYNETCF
        if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && c == '\xFEFF')
        {
            // Dev11 450846 quirk:
            // NetCF treats the BOM as a whitespace character when performing trim operations.
            return true;
        }
        else
#endif
        {
            return false;
        }
    }

运行时,内循环中的输出仅显示所有条目上姓氏数组(列侬)和i(3)的最后一个值。我想要实现的输出是每个名字,姓氏将分发给所有名字(例如John Harrison,John Starr等),索引(i)将从0增加到3.谢谢。

3 个答案:

答案 0 :(得分:1)

你想要这样的东西吗?



var arr = [];
var names = [{
  name: 'George'
}, {
  name: 'Ringo'
}, {
  name: 'Paul'
}, {
  name: 'John'
}];
var surnames = [{
  surname: 'Harrison'
}, {
  surname: 'Starr'
}, {
  surname: 'McCartney'
}, {
  surname: 'Lennon'
}];

for (i = 0; i < names.length; i++) {
  arr.push({
      index: i,
      firstname: names[i].name,
      surname: surnames[i].surname
    });
  }
  console.log(arr);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个,

for (i = 0; i < names.length; i++) {
       var obj = new Object;
        obj['name'] = names[i];
        obj['name']['surname'] = surnames[i].surname;
        obj['index'] = i;
        arr.push(obj);

}
   console.log(arr);

答案 2 :(得分:0)

看起来你想要姓氏的所有名字的笛卡尔积。

试试这个

&#13;
&#13;
 var arr = [];
 var names = [{
   name: 'George'
 }, {
   name: 'Ringo'
 }, {
   name: 'Paul'
 }, {
   name: 'John'
 }];
 var surnames = [{
   surname: 'Harrison'
 }, {
   surname: 'Starr'
 }, {
   surname: 'McCartney'
 }, {
   surname: 'Lennon'
 }];

 for (i = 0; i < names.length; i++) 
 {
   for (j = 0; j < surnames.length; j++) 
   {
     var tmpObj = JSON.parse(JSON.stringify(names[i]));
     tmpObj['surname'] = surnames[j].surname;
     tmpObj['index'] = i;
     arr.push(tmpObj);
   }
 }
 console.log(arr);
&#13;
&#13;
&#13;

或者您也可以

Object.create(names[i]) 

而不是

JSON.parse(JSON.stringify(names[i]));