二元运算符 标准
- 假如操作数是目标,则目标会转换成原始值
- 假如操作数是字符串数组,则另一个操作数也会变成字符串数组,开展字符串拼接
- 不然,2个操作数也将转换为数字或 NaN,开展加减法实际操作
目标数据信息变为原始记录种类系数的方式
Symbol.ToPrimitive
Object.prototype.valueOf
Object.prototype.toString
优先
- 假如
[Symbol.toPrimitive](hint)
方式存有,优先选择启用,忽视valueOf
和toSting
方式 - 不然,假如期待是
"string"
—— 先启用obj.toString()
假如回到并不是原始值,再次启用obj.valueOf()
- 不然,假如期待是
"number"
或"default"
先启用obj.valueOf()
假如回到并不是原始值,再次启用obj.toString()
- 假如未声明
[Symbol.toPrimitive](hint)
,期待string,这时toString()
和valueOf()
也没有回到原始值会抛出异常
const obj = {
value: 10,
valueOf() {
return this;
},
toString() {
return this;
}
};
console.log("hello" obj);
[] 的原始值
typeof [][Symbol.ToPrimitive] // undefined
[].valueOf // []
[].toString() // ""
{} 的原始值
typeof {}[Symbol.ToPrimitive] // undefined
{}.valueOf() or ({}).valueof() // {}
({}).to String() // '[object Object]'
[] []
变换流程:
- [].toString() [].toString()
- "" ""
- ""
[] {}
- [].toStrin() ({}).toString()
- "" "[object Object]"
- "[object Object]"
{} []
- {}; []
- []
- ""
- 0
{} {}
- {}; {}
- '[object Object]'
- NaN
留意以前 chrome
核心电脑浏览器会把其分类后变为 ({} {})
转换成变成 '[object Object][object Object]'
Symbol.toPrimitive(hint)
hint
(暗示着期待)-"string"
hint
"number"
hint
"default"
hint "string"
window.alert(obj)
- 模版字符串数组
`${obj}
test[obj] = 123
const obj = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 10;
}
if (hint === "string") {
return "hello";
}
return true;
}
};
window.alert(obj); // "hello"
console.log(`${obj}`); // "hello"
obj[obj] = 123;
console.log(obj); // {hello: 123, Symbol(Symbol.toPrimitive): ƒ}
console.log(Object.keys(obj)); // [ "hello" ]
hint "number"
- 一元 ,偏移
-
、*
、/
等算术操作符Math.pow
、String
、prototype.slice
等许多内部结构方式
const obj = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 10;
}
if (hint === "string") {
return "hello";
}
return true;
}
};
console.log("一元 ", obj);
console.log("偏移操作符", obj >> 0);
console.log("加减法", obj 5); // 留意加减法的 hint 是 default
console.log("加减法", obj - 5);
console.log("乘除法", obj * 5);
console.log("乘法", obj / 5);
console.log("超过:", obj > 5);
console.log("超过:", obj < 5);
console.log("高于或等于:", obj >= 5);
console.log("高于或等于:", obj <= 5);
console.log("高于或等于:", obj !== 5);
// 别的期待是整数金额的办法
console.log("Math.pow", Math.pow(2, obj));
打印出结论:
hint - "default"
- 二元+
==
、!=
const obj = {
[Symbol.toPrimitive](hint) {
if (hint === "number") {
return 10;
}
if (hint === "string") {
return "hello";
}
return true;
}
};
console.log("求和", obj 5); // 求和 6
console.log("这些与", obj == 5); // 这些与 false
console.log("并不等于", obj != 5); // 并不等于 true