+ javascript 中表达式之前的运算符:它有什么作用?
我正在仔细阅读 underscore.js 库,我发现了一些我没有找到的东西之前遇到过:
if (obj.length === +obj.length) { ... }
+
运算符在那里做什么?对于上下文,这里有一个直接链接到该部分文件。
I was perusing the underscore.js library and I found something I haven't come across before:
if (obj.length === +obj.length) { ... }
What is that +
operator doing there? For context, here is a direct link to that part of the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 JavaScript 中,一元
+
运算符可用于将值转换为数字。 Underscore 似乎正在测试.length
属性是否为数字,否则它将不等于自身转换为数字。The unary
+
operator can be used to convert a value to a number in JavaScript. Underscore appears to be testing that the.length
property is a number, otherwise it won't be equal to itself-converted-to-a-number.根据MDN:
According to MDN:
这是确保 obj.length 是数字而不是潜在字符串的一种方法。这样做的原因是,如果长度(无论出于何种原因)是字符串变量,例如“3”,则 === 将失败。
It's a way of ensuring that obj.length is a number rather than a potential string. The reason for this is that the === will fail if the length (for whatever reason) is a string variable, e.g. "3".
检查
obj.length
是否属于number
类型是一个很好的技巧。您会看到,+
运算符可用于字符串强制转换。例如:这是可能的,因为
+
运算符将字符串"3"
强制转换为数字3
。因此结果是10
而不是"37"
。另外,JavaScript 有两种类型的相等和不等运算符:
3 === "3"
表示 false)。3 == "3"
表示 true)。严格的平等和不平等并不强制价值。因此数字
3
不等于字符串"3"
。正常的平等和不平等确实会强制价值。因此数字3
等于字符串"3"
。现在,上面的代码只是使用
+
运算符将obj.length
强制转换为数字,并严格检查强制转换前后的值是否相同(即>obj.length
类型为number
)。它在逻辑上等价于以下代码(只是更简洁):It's a nice hack to check whether
obj.length
is of the typenumber
or not. You see, the+
operator can be used for string coercion. For example:This is possible because the
+
operator coerces the string"3"
to the number3
. Hence the result is10
and not"37"
.In addition, JavaScript has two types of equality and inequality operators:
3 === "3"
expresses false).3 == "3"
expresses true).Strict equality and inequality doesn't coerce the value. Hence the number
3
is not equal to the string"3"
. Normal equality and inequality does coerce the value. Hence the number3
is equal to the string"3"
.Now, the above code simply coerces
obj.length
to a number using the+
operator, and strictly checks whether the value before and after the coercion are the same (i.e.obj.length
of the typenumber
). It's logically equivalent to the following code (only more succinct):