在Javascript中将对象推送到另一个数组后,为什么我的对象变成了数组?

时间:2017-10-21 04:02:15

标签: javascript arrays

JS新手在这里。我正在学习将嵌套数组转换为包含对象的数组。

我的问题:将var outObj = {};推入outobj{}后,为什么outArr[]会变成数组? (请参阅本文末尾的预期和实际输出)提前感谢您的帮助。

function transformEmployeeData(inArr) {
  var outArr = []; 

  for(var x = 0; x < inArr.length; x++){

    var outObj = {}; // The obj that will be stores in outArr[]
    var a1 = inArr[x]; 
    //console.log(a1 + '\n');

    for(var y = 0; y < a1.length; y++){
      outObj[a1[y][0]] = a1[y][1];
      //console.log(outObj[a1[y][0]]);
    }
    outArr.push(outObj);
  }
  return arr;
}

var arr = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];
console.log(transformEmployeeData(arr)); 
/* 
Expected Output:
[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

Actual Output:
[ [ [ 'firstName', 'Joe' ],
    [ 'lastName', 'Blow' ],
    [ 'age', 42 ],
    [ 'role', 'clerk' ] ],
  [ [ 'firstName', 'Mary' ],
    [ 'lastName', 'Jenkins' ],
    [ 'age', 36 ],
    [ 'role', 'manager' ] ] ]
*/

1 个答案:

答案 0 :(得分:1)

outArr函数调用

返回arr而不是transformEmployeeData()
return outArr;