We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第522天 把对象转换到数字类型是如何转换的?
#298,#409
3+1官网
我也要出题
The text was updated successfully, but these errors were encountered:
1、如果对象有valueOf方法,则调用该方法,并返回相应的结果;
2、当调用valueOf返回的依然不是数字,则会调用对象的toString方法,并返回相应的结果;
3、否则抛出异常。
Sorry, something went wrong.
toNumbere = ( o, parsed = (o.valueOf && o.valueOf()) || o.toString(), isN = /^[-+]{0,1}\d*\.{0,1}\d+$/.test(parsed) ) => (isN && parseFloat(parsed)) || NAN;
首先会查找对象是否实现了[Symbol.toPrimitive]方法。
[Symbol.toPrimitive]
一般来说[Symbol.toPrimitive]方法决定了valueOf()和toString()的调用顺序,该方法接受一个参数 hint,当 hint为number时,则调用valueOf()方法;为string时,则调用toString()方法。
valueOf()
toString()
hint
number
string
例:
const obj = { // 默认[Symbol.toPrimitive] 方法,删掉不影响输出结果 [Symbol.toPrimitive](hint) { if(hint === 'number') { return this.valueOf(); } else if (hint === 'string') { return this.toString(); } return true; }, valueOf() { return 42; }, toString() { return 'foo'; } }; console.log(obj * 2); // 84 console.log(`Hello, ${obj}!`); // "Hello, foo!"
No branches or pull requests
第522天 把对象转换到数字类型是如何转换的?
#298,#409
3+1官网
我也要出题
The text was updated successfully, but these errors were encountered: