【发布时间】:2020-07-12 23:54:08
【问题描述】:
考虑以下 javascript
var test = ['1', '2', '3'];
在控制台中,输入
test.indexOf('1') > -1;
结果为真。
现在添加基本的 Not 运算符!。
!test.indexOf('1') > -1;
结果也是正确的,但我预计结果是错误的。为什么是真的?
【问题讨论】:
标签: javascript
考虑以下 javascript
var test = ['1', '2', '3'];
在控制台中,输入
test.indexOf('1') > -1;
结果为真。
现在添加基本的 Not 运算符!。
!test.indexOf('1') > -1;
结果也是正确的,但我预计结果是错误的。为什么是真的?
【问题讨论】:
标签: javascript
这是因为! 的operator precedence 比> 高,所以首先,test.indexOf() 的结果被否定,在你的例子中导致 0 被否定,所以它变成了true。然后在不等式的上下文中使用它,它将true 转换为1 以进行比较。作为1 > -1,你会得到true的结果。
【讨论】:
你得到了true,因为你否定了左手值
!test.indexOf('1')
不是整个表达方式
!(test.indexOf('1') > -1).
换句话说:
!test.indexOf('1') > -1 // expected true
不一样
!(test.indexOf('1') > -1) // expected false
像数学语句:
5*2+2 // not the same as 5*(2+2)
【讨论】: