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
注意"Boolean 转字符串"这行结果指的是 true 转字符串的例子 null == 0 => false
var bool = true console.log(bool.toString())// "true"
JavaScript 有两种比较方式:严格比较运算符和转换类型比较运算符。对于严格比较运算符(===)来说,仅当两个操作数的类型相同且值相等为 true,而对于被广泛使用的比较运算符(==)来说,会在进行比较之前,将两个操作数转换成相同的类型。对于关系运算符(比如 <=)来说,会先将操作数转为原始值,使它们类型相同,再进行比较运算。
比较操作符会为两个不同类型的操作数转换类型,然后进行严格比较。当两个操作数都是对象时,JavaScript会比较其内部引用,当且仅当他们的引用指向内存中的相同对象(区域)时才相等,即他们在栈内存中的引用地址相同。
console.log({a: 1} == true);//false console.log({a: 1} == "[object Object]");//true
对象转原始类型,会调用内置的[ToPrimitive]函数,对于该函数而言,其逻辑如下:
var obj = { value: 1, toString(){ return 2 }, valueOf(){ return 3 }, [Symbol.toPrimitive](){ return 4 } } console.log( obj + 1)// 5
var b = {} console.log(+b)//NaN console.log(b + 1)//“[object object]1” console.log(1 + b)//“1[object object]” console.log(b + '')//“[object object]”
var a = { value: 1, toString: function(){ return this.value++ } } if(a == 1 && a == 2){ console.log(true) } 或者 var a = { value: 1, valueOf: function(){ return this.value++ } } if(a == 1 && a == 2){ console.log(true) }
console.log({} + [])//"[object object]" console.log([2] - [] + function () {})//"2function(){}" 函数是会转换为源代码字符串的。
var a = { value: 0, [Symbol.toPrimitive](hint){ console.log(hint) return ++this.value } } if(a == 1 && a == 2 && a == 3){ console.log("in") }
let a = [1, 2, 3] a['join'] = function () { return this.shift() } if (a == 1 && a == 2 && a == 3) { console.log('成立') }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
1. 类型转换种类
2. 转换
3. == 和 ===
左右两边不仅值要相等,类型也要相等
4. ==类型转换规则
5. 对象转原始类型流程
对象转原始类型,会调用内置的[ToPrimitive]函数,对于该函数而言,其逻辑如下:
注:图片截取自MDN
6 运算符的类型转换
注意点:
(+号对于对象的转换)
7. 拓展
首先右边![]得到布尔值,由于[]作为一个引用类型转换为布尔值为true, 因此![]为false,进而在转换成数字,变为0。左边空数组转换成数字也为0,所以答案为true
对象如果是数组的话,当我们不重写其toString()方法,在转换为字符串类型的时候,默认实现就是将调用join()方法的返回值作为toString()的返回值
参考:
The text was updated successfully, but these errors were encountered: