我注意到 array.join 的输出不正确,其中包含 (\r) 字符的字符串数组。这是我的代码和输出:
var list = [
"one\r",
"two\r",
"three\r",
"four\r"]
console.log(list); // ok, output: [ 'one\r', 'two\r', 'three\r', 'four\r' ]
console.log(list.join(',')); // incorrect, outputs: ,foure
它在 chrome/firefox 控制台中工作正常,但在 Nodejs 中不行。 如果重要的话,我在 linux mint 18.3 上使用 Node 6.11.3
我可以为此采取解决方法,但我更感兴趣的是为什么会发生这种情况。
最佳答案
实际上你的代码中字符串连接成功了,输出结果“,foure”是由字符'\r'引起的,这称为“换行符”,Linux/macOS终端中的换行符将光标移动到a的开头线,所以:
- “one\r”输出:“one”
- “one\r,two\r”输出:“two”
- “一\r,二\r,三\r”输出:“三”
- “一\r,二\r,三\r,四\r”输出:“四”
最后一个字符“e”来自“三”,\r
不是“新行”。
使用“\n”回车
输出新行,只需将其放入“join(',\n')”中,而不是放入数组元素中。
var list = [
"one",
"two",
"three",
"four"];
console.log(list); // ok, output: [ 'one', 'two', 'three', 'four' ]
console.log(list.join(',\n'));
关于arrays - NodeJS : incorrect result of array. 加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189971/