gpt4 book ai didi

javascript - 为什么 JSON.parse 适用于 1 个元素的数组?

转载 作者:行者123 更新时间:2023-12-01 23:20:26 25 4
gpt4 key购买 nike

文档似乎说 JSON.parse 应该只适用于字符串:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

但是,它似乎适用于长度为 1 的数组整数值:

-> JSON.parse([123])
<- 123
-> JSON.parse(["[123]"])
<- [123]

但是,如果有多个值,它就会中断:

-> JSON.parse([123, 456])
<- VM439:1 Uncaught SyntaxError: Unexpected token , in JSON at position 3
at JSON.parse (<anonymous>)
at <anonymous>:1:6

或单个字符串值:

-> JSON.parse(['string'])
<- VM586:1 Uncaught SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6

有谁知道为什么会这样?

最佳答案

因为参数很可能被强制转换为字符串。

[123] + '' 结果为 '123'JSON.parse('123') 结果为 123

[123, 4] + '' 结果为 '123,4',和 JSON.parse('123,4') 导致语法错误。

关于javascript - 为什么 JSON.parse 适用于 1 个元素的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68169355/

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