如何使用“+string"进行类型强制?在 Javascript 中工作? [英] How does type coercion with "+string" work in Javascript?

查看:34
本文介绍了如何使用“+string"进行类型强制?在 Javascript 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个,+string"将字符串转换为数字(特别是,在字符串或字符串变量前面使用加号运算符进行类型强制),但找不到相关文档或讨论满足我的兴趣.我的印象是它很懒惰或者可能会产生意想不到的副作用,但我想更好地理解它.任何见解表示赞赏.

I came across this recently, "+string" converting the string to a number (specifically, using the plus operator in front of a string or string variable for type coercion), but wasn't able to find documentation or discussion that satisfied my interested. I get the impression it's lazy or could have unintended side effects, but I want to understand it better. Any insight is appreciated.

推荐答案

作为 ECMAScript 规范第 12.5 节中进行了描述.6:

12.5.6 一元 + 运算符

注意     一元 + 运算符将其操作数转换为数字类型.

NOTE       The unary + operator converts its operand to Number type.

因此在 JavaScript 中,一元 + 运算符(例如,+x)将始终转换表达式 x 变成一个数字.换句话说,以下语句是等效的:

So in JavaScript, the unary + operator (e.g., +x) will always convert the expression x into a number. In other words, the following statements are equivalent:

var x = Number('1234');
var y = +'1234';

这也适用于任何变量,不仅仅是字符串或数字.如果您尝试转换的对象不是字符串或数字,则将调用该对象的 toString() 方法将对象转换为字符串,然后将其转换为数字.例如:

This also works on any variable, not only strings or numbers. If the object you try to convert is not an string or number, then the toString() method of that object will be called to convert the object into a string, and then that will be converted into a number. For example:

var obj = {
  toString: function() { return '9999'; }
};
var num = +obj; // = 9999

这篇关于如何使用“+string"进行类型强制?在 Javascript 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆