Skip to content
New issue

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

[js] 第522天 把对象转换到数字类型是如何转换的? #2928

Open
haizhilin2013 opened this issue Sep 18, 2020 · 3 comments
Open
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第522天 把对象转换到数字类型是如何转换的?

#298#409

3+1官网

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label Sep 18, 2020
@iyanming
Copy link

1、如果对象有valueOf方法,则调用该方法,并返回相应的结果;

2、当调用valueOf返回的依然不是数字,则会调用对象的toString方法,并返回相应的结果;

3、否则抛出异常。

@cool-delete
Copy link

cool-delete commented Sep 19, 2020

toNumbere = (
  o,
  parsed = (o.valueOf && o.valueOf()) || o.toString(),
  isN = /^[-+]{0,1}\d*\.{0,1}\d+$/.test(parsed)
) => (isN && parseFloat(parsed)) || NAN;

@wheatup
Copy link

wheatup commented Sep 20, 2020

首先会查找对象是否实现了[Symbol.toPrimitive]方法。

一般来说[Symbol.toPrimitive]方法决定了valueOf()toString()的调用顺序,该方法接受一个参数 hint,当 hintnumber时,则调用valueOf()方法;为string时,则调用toString()方法。

例:

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!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

4 participants