简体   繁体   English

什么是一元+用于Javascript?

[英]What is unary + used for in Javascript?

I have found some code from Underscore.js 我从Underscore.js找到了一些代码

  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    if (obj.length === +obj.length) results.length = obj.length;
    return results;
  };

I would like to know what if (obj.length === +obj.length) does? 我想知道if (obj.length === +obj.length)是做什么的?

+length is a method to convert anything to a number. +length是将任何内容转换为数字的方法。

If it's a number, the value doesn't change, and the comparison returns true. 如果它是数字,则值不会更改,并且比较返回true。
If it's not a number, the assertion is false. 如果它不是数字,则断言是错误的。

That's the unary + operator. 那是一元+算子。 This website has a great article on its uses with the different data types in javascript. 这个网站有一篇关于它在javascript中使用不同数据类型的精彩文章。

http://xkr.us/articles/javascript/unary-add/ http://xkr.us/articles/javascript/unary-add/

I'll steal the introduction, but it is really worth reading if you are into javascript. 我会窃取介绍,但如果你使用的是javascript,那真的值得一读。

In JavaScript it is possible to use the + operator alone before a single element. 在JavaScript中,可以在单个元素之前单独使用+运算符。 This indicates a math operation and tries to convert the element to a number. 这表示数学运算并尝试将元素转换为数字。 If the conversion fails, it will evaluate to NaN. 如果转换失败,它将评估为NaN。 This is especially useful when one wants to convert a string to a number quickly, but can also be used on a select set of other types. 当想要快速将字符串转换为数字时,这尤其有用,但也可以在其他类型的选择集上使用。

The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number. 当在字符串以外的类型上使用时,一元+运算符将在内部尝试调用valueOf()或toString()(按此顺序),然​​后尝试将结果转换为数字。 Thusly, the unary + operator can successfully convert many of the native JS types with certain restrictions: 因此,一元+运算符可以成功地转换许多具有某些限制的本机JS类型:

This is test, if obj.length is number. 如果obj.length是数字,这是测试。

Doing arithmetic operation on string converts it to integer (and + is unary operation.. which doesn't do anything :-) ), and === operator does type-wise comparsion 对字符串进行算术运算会将其转换为整数(并且+是一元运算..它不执行任何操作:-)),而===运算符执行类型比较

a === b <=> (a == b) && (typeof a) == (typeof b)

I will suggest you to try this 我建议你试一试

console.log(typeof +"3") = number console.log(typeof +“3”)=数字

console.log(typeof "3") = string console.log(typeof“3”)= string

This makes everything clear. 这使一切都清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM