Javascript JSON.parse使用零元素数组(node.js)

Javascript JSON.parse使用零元素数组(node.js),javascript,arrays,json,node.js,parsing,Javascript,Arrays,Json,Node.js,Parsing,根据文档,将第一个参数作为字符串。 我发现了一个意想不到的行为: try { const a = JSON.parse([ '{"helloworld": 1}', ]); console.log(a); } catch (ex) { console.error(ex); } 我预计它会失败,因为提供的输入参数是数组。相反,JSON.parse成功解析数组[0]元素并将其打印出来(在node.js中) 但是,如果传递包含两个元素的数组,JSON.

根据文档,将第一个参数作为字符串。 我发现了一个意想不到的行为:

try {
    const a = JSON.parse([
        '{"helloworld": 1}',
    ]);
    console.log(a);
} catch (ex) {
    console.error(ex);
}
我预计它会失败,因为提供的输入参数是数组。相反,
JSON.parse
成功解析数组[0]元素并将其打印出来(在node.js中)

但是,如果传递包含两个元素的数组,
JSON.parse
将出错

try {
    const b = JSON.parse([
        '{"hello": 1}',
        '{"hello2": 2}',
    ]);
    console.log(b);
} catch (ex) {
    console.error(ex);
}

为什么会这样?

JSON.parse是一个需要字符串的内部JS方法。但是,如果给定了另一个类型,它会将其转换为字符串。对于数组,到字符串的转换是
array.join(',')


因此,当有一个元素时,它只会将第一个元素转换为字符串。当为JSON.parse提供一个包含多个元素的数组时,它将出错,因为输入的JSON无效。

取决于数组中的内容。。。从技术上讲,类似于
['{“hello”:1',““hi”:2}']
的东西是有效的…:Ptrue:)但我不建议这样做是为了避免来自其他开发人员的OMG