无法在JS中将数据推送到空数组中

时间:2018-12-03 09:34:00

标签: javascript arrays

我正在尝试将数据推入空值,但返回的空数组。 我正在尝试以json格式推送。在行中推送值[]

 Result {
      command: 'SELECT',
      rowCount: 2,
      oid: NaN,
      rows:
       [ anonymous { username: 'pewdiepie' },
         anonymous { username: 'tseries' } ],

代码:

var newList = new Array();

data => {
        for(var  i = 0; i< data.length; i++){
         newList.push(data.rows[i].username)
       }}

2 个答案:

答案 0 :(得分:1)

i < data.length应该是i < data.rows.lengthdata是容器对象,data.rows是您要遍历的数组。

但您可以使用map来代替循环:

newList = data.rows.map(e => e.username);

forEach

data.rows.forEach(e => newList.push(e.username));

答案 1 :(得分:0)

There's just one error buddy. The for loop should range from 0 to length of rows inside the object. But you are doing [object].length. Hence it isn't giving the right output.

Here is the working code:

var data = {
  command: 'SELECT',
  rowCount: 2,
  oid: NaN,
  rows: [
    anonymous = {
      username: 'pewdiepie'
    },
    anonymous = {
      username: 'tseries'
    }
  ]
}

var newList = new Array();


for (var i = 0; i < data.rows.length; i++) {
  newList.push(data.rows[i].username);
}


console.log(newList);