gpt4 book ai didi

Javascript 无法推送到函数内部的全局数组

转载 作者:行者123 更新时间:2023-11-30 15:37:40 25 4
gpt4 key购买 nike

<分区>

我有一个文件夹,里面装满了 json 文件,我正试图将它们全部推送到一个数组中。但是,外部数组是空白的。任何关于为什么会发生这种情况或解释更好方法的帮助将不胜感激。

var fs = require('fs');
var dataFolder = './jsonData/';

var arr = [];
fs.readdir(dataFolder, (err, files) => {
files.forEach(file => {
fs.readFile(dataFolder + file, 'utf8', function (err, data) {
if (err) throw err;
arr.push(data);
console.log (arr); // correct output
})
})
})
console.log (arr); //output is []

很抱歉它看起来很丑,但这是内部数组的一些输出:

[ '{\n "title": "A New Kind of Science [Hardcover]",\n "author": "Stephen Wolfram",\n "price": "$20.73",\n "shippingWeight": "5.6 磅",\n "isbn10": "1579550088"\n}' ]

[ '{\n "title": "A New Kind of Science [Hardcover]",\n "author": "Stephen Wolfram",\n "price": "$20.73",\n "shippingWeight": "5.6 磅",\n "isbn10": "1579550088"\n}', '{\n "title": "I Wear the Black Hat: Grapping with Villains (Real and Imagined) [Hardcover]",\n "author": "Chuck Klosterman",\n "price": "$15.49",\n "shippingWeight": "2.2 磅",\n "isbn10": "1439184496"\n}' ]

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com