创建了一个文件名big.file并存储了值
const fs = require('fs');
const file = fscreateWriteStream('./big.file');
for(let i=0; i<= 2; i++) {
file.write('1\r\n2\r\n3\r\n');
}
file.end()
我阅读了该文件,并尝试查找奇数的计数
const file2 = fs.readFile('./big.file','utf8', (err,lines) = {
if(err) throw err;
console.log(lines);
const numbers = lines.map(Number);
const oddNumbers = numbers.filte(n => n%2 ===1);
console.log('odd number count:', oddNumbers.length);
});
这是我的输出:
C:\projects\rough>node index.js
1
2
3
C:\projects\rough\index.js:13
const numbers = lines.map(Number);
^
最佳答案
lines
是一个字符串,而不是一个数组,因此您会收到此错误。 String
没有 map()
方法。
要获取数组,您需要按 \n
(换行)字符拆分数据。
fs.readFile('./big.file', 'utf8', (err, data) = {
if (err) throw err;
const lines = data.split('\n');
console.log(lines);
const numbers = lines.map(Number);
const oddNumbers = numbers.filter(n => n%2 ===1);
console.log('Odd numbers count:', oddNumbers.length);
});
关于javascript - Node.js 奇数计数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004727/