现在我正在阅读你不知道的 JS 类型和语法第 4 章,在那里我遇到了这个关于强制转换的例子。 https://repl.it/D7w2
var i = 2;
Number.prototype.valueOf = function() {
console.log("called"); //this logs twice
return i++;
};
var a = new Number( 42 );
if (a == 2 && a == 3) {
console.log( "Yep, this happened." ); //this is logged
}
我不明白为什么事情不差一点。由于 var i 从 2 开始,当它命中 a == 2 时不应该返回 3 然后当 a == 3 运行时不应该返回 4?
最佳答案
不是,因为你用的是后增量。这会返回变量递增之前的旧值。
如果您使用预递增 ++i
,那么它会递增变量并返回新值。
var i = 2;
Number.prototype.valueOf = function() {
console.log("called"); //this logs twice
return ++i;
};
var a = new Number( 42 );
if (a == 2 && a == 3) {
console.log( "Yep, this happened." ); //this is logged
}
关于javascript - 调用 valueOf 时的操作顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39458886/