Javascript 将空字符串添加到未定义的过程(如果为true)

Javascript 将空字符串添加到未定义的过程(如果为true),javascript,runtime-error,undefined,Javascript,Runtime Error,Undefined,它让我发疯,我看不到它,但它是一个JavaScript错误: 添加到空字符串中的每个未定义变量的计算结果均为true!(?) 注意: var x = {a: 1}; console.log('----y = x[\'b\']----'); var y = x['b']; //can't do x[b] if(y) console.log('f...ed!'); else console.log('we are not f...ed!'); console.log('y='+y);

它让我发疯,我看不到它,但它是一个JavaScript错误:

添加到空字符串中的每个未定义变量的计算结果均为true!(?)

注意:

var x = {a: 1};

console.log('----y = x[\'b\']----');
var y = x['b']; //can't do x[b]
if(y)
   console.log('f...ed!');
else
   console.log('we are not f...ed!');
console.log('y='+y);
console.log((typeof y)+' (typeof y)');
console.log((y == undefined)+' (y == undefined)');
console.log((y === undefined)+' (y === undefined)');
console.log((y == null)+' (y == null)');
console.log((y === null)+' (y === null)');
console.log('-------------------------');
console.log('----z = x[\'b\']+\'\'----');
var z = x['b']+''; //can't do x[b]
if(z)
   console.log('f...ed!');
else
   console.log('we are not f...ed!');
console.log('z='+z);
console.log((typeof z)+' (typeof z)');
console.log((z == undefined)+' (z == undefined)');
console.log((z === undefined)+' (z === undefined)');
console.log((z == null)+' (z == null)');
console.log((z === null)+' (z === null)');
结果是:

----y = x['b']----
we are not f...ed!
y=undefined
undefined (typeof y)
true (y == undefined)
true (y === undefined)
true (y == null)
false (y === null)
-------------------------
----z = x['b']+''----
f...ed!
z=undefined
string (typeof z)
false (z == undefined)
false (z === undefined)
false (z == null)
false (z === null)
我真的认为我们是疯了!(IE8、FF、Chrome、Opera都同意这一点!)


jsIDLE:

是,因为它已转换为字符串:

'' + undefined --> "undefined"

如设计所示,请参见规范:

这不是一个bug,如果是的话,你可能不会让每个浏览器都以这种方式实现它

是傻瓜吗?当然很难想象程序员会希望
undefined+“foo”
给出
“undefinedfoo”
作为答案。大多数其他语言要么什么也不做,要么插入一个空字符串(与什么都不做相同),要么抛出一个错误,但为什么它在Javascript中这样工作(或它的智慧)将是一个意见问题,而不是事实,对于堆栈溢出来说,这不是一个合适的问题


因此,如果您的问题是“这是一个bug吗?”,那么简短的答案是“否”。

这里有问题吗?我无法想象为什么你会认为这种行为是一个“JavaScript错误”,正如你所指出的,这种行为在不同的实现中是一致的。仅仅因为你认为事情应该以某种方式运作并不意味着它们应该如此。参见第143页:另外,我不认为任何人对你几乎没有掩饰的亵渎印象深刻。如果你想让人们认真对待你的问题,就不要提了。@centurian:
s/你应该得到一个“逻辑”的假结果/你没有阅读任何文档,而是用你的假假设来满足自己的要求/
是的,我刚刚确认了:z==“undefined”给出的是真的(一个字符串!)。我在等空字符串(!)