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类型转换相关点 #25

Open
lizheng0515 opened this issue Jun 22, 2020 · 0 comments
Open

JS类型转换相关点 #25

lizheng0515 opened this issue Jun 22, 2020 · 0 comments

Comments

@lizheng0515
Copy link
Owner

  • js中的类型名的强制类型转换
    Number(mix) String(mix)Boolean(mix)

  • js中的类型隐式转换的条件是什么?
    各种运算符,包括==比较运算符,还有++,大于小于等等

  • js中强制类型转换的两种方式是什么?
    转换函数:parseInt(string,radix)parseFloat(string)toString(radix)
    构造方法:Number(mix)Boolean(mix)

  • 对象转原始类型是根据什么流程运行的?
    对象转原始类型,会调用内置的[ToPrimitive]函数,对于该函数而言,其逻辑如下:
    如果有Symbol.toPrimitive()方法,优先调用再返回
    调用valueOf(),如果转换为原始类型,则返回
    调用toString(),如果转换为原始类型,则返回
    如果都没有返回原始类型,会报错

var obj = {
    value: 3,
    valueOf () {
        return 4
    },
    toString () {
        return '5'
    },
    [Symbol.toPrimitive] () {
        return 6
    }
}
console.log(obj + 1) // 输出7
var obj = {
    value: 3,
    valueOf () {
        return 4
    },
    toString () {
        return '5'
    },
}
console.log(obj + 1) // 输出5
var obj = {
    value: 3,
    toString () {
        return '5'
    },
}

console.log(obj + 1) // 输出51 注意 toString 返回的是一个字符串5
var obj = {
    value: 3,
}
console.log(obj + 1) // 输出51 注意 toString 返回的是一个字符串5
如何让if(a == 1 && a == 2)条件成立?
var a = {
  value: 0,
  valueOf: function() {
    this.value++;
    return this.value;
  }
};
console.log(a == 1 && a == 2);//true
```js

[] == ![]结果是什么?为什么?
== 中,左右两边都需要转换为数字然后进行比较。
[] 转换为数字为0。
![]  首先是转换为布尔值,由于[]作为一个引用类型转换为布尔值为true,
因此 ![] 为f alse,进而在转换成数字,变为0。

```js
0 == 0  结果为 true
console.log({a: 1} == true); // false
console.log({a: 1} == "[object Object]"); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant