arrays - NodeJS : incorrect result of array. 加入

标签 arrays node.js

我注意到 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/

相关文章:

java - ArrayIndexOutOfBounds 异常,但没有越界?

javascript - 使用纯 JavaScript 或 Lodash 进行 JSON 数组操作

mysql - 使用 Node JS 和 Sequelize 连接到 MySql

c# - 使用 Linq 添加数组数组的索引位置值

java - 为 ListObjectClass 中的每个对象创建 ID

node.js - Laravel Elastic Beanstalk,无法安装运行 npm?

javascript - JS - 未处理的 promise

javascript - 使用 JSONStream.parse 解析整个对象

Java 类垄断游戏

node.js - Ionic2 安装后的 Ionic 安装