【问题标题】:Method push dont work in nodejs after conversion转换后方法推送在nodejs中不起作用
【发布时间】:2021-11-17 23:59:58
【问题描述】:

我正在尝试使用push method 将数据附加到Array 中。我通过json file 获得了数组,我已经通过fs.readFileSynch 读取了该数组,然后使用JSON.parse() 方法将该数据转换为对象。下面是我的代码以获得更多解释:

let data = fs.readFileSync("my_jsonfile_here"),(err)=>{
    if(err) return console.log(err);
});
data = JSON.parse( data.toString() ); // convert it to object
let appendDATA = data.push({name:"zadi"}) ; //adding data
console.log(appendDATA) // return number  why ???????????? 
// I was expecting this [{name:"donald"},{name:"zadi"}] as a result 

我的 json 文件如下所示:

[
  {"name":"donald"}
]

【问题讨论】:

  • 为什么要编号?因为push 方法返回调用该方法的对象的新长度属性。你应该 console.log(data); 而不是 appendData

标签: node.js arrays json push


【解决方案1】:

Array.push 修改数组,不返回你想要的。

只需使用:

data.push({name:"zadi"});
console.log(data)

【讨论】:

  • 编程就是编程..谢谢我忘记了
  • 你说 Array.push modifies the array, and doesn't return what you want 但你确实做到了
  • 怎么回事?关键是您要使用数组本身(现在已修改),而不是返回值。
【解决方案2】:

如果查看Array.push文档,该方法返回推送记录后的数组长度

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push#return_value


提示:我认为最好使用回调或承诺来读取文件

const fsAsync = require('fs/promises');

(async () => {
  try {
    const body = await fsAsync.readFile('my_jsonfile_here');

    const data = JSON.parse(body.toString());
    const length = data.push({ name: 'zadi' });

    console.log('length', length);
    console.log('data', data);
  } catch (error) {
    console.error(error);
  }
})();

// Or use callback
const fs = require('fs');

fs.readFile('my_jsonfile_here', (error, body) => {
  if (error) {
    console.error(error);
    return;
  }

  const data = JSON.parse(body.toString());
  const length = data.push({ name: 'zadi' });

  console.log('length', length);
  console.log('data', data);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2015-09-02
    相关资源
    最近更新 更多