给定:
var obj={0:21,1:22}
和
var arr=[21,22]
为什么 parseInt(obj)
返回 NaN
,而 parseInt(arr)
返回 21
?
我有一个函数,我要传递一个 int
、一个散列类型 object
或一个普通的 array
。我期待 parseInt
为 object
和 array
返回 NaN
,从而简化参数检查。给了什么?
最佳答案
这是因为 parseInt
试图在解析为整数之前将第一个参数强制转换为字符串。 String(obj)
返回[object Object]”
无法解析,但是String([21,23])
返回"21,23"
,parseInt
对其进行解析,直到到达无法解析的字符。
参见 the parseInt
spec :
Let
inputString
be ? ToString(string
).
(将输入强制转换为字符串)。
If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.
(删除以非数字字符开头的字符串的任何部分,因此 "21,23"
-> "21"
)。
关于javascript - 为什么 parseInt 无法在 Javascript 中正确测试数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263114/