Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - 空数组似乎同时等于true和false(Empty arrays seem to equal true and false at the same time)

Empty arrays are true but they're also equal to false.(空数组为true,但也等于false。)

var arr = []; console.log('Array:', arr); if (arr) console.log("It's true!"); if (arr == false) console.log("It's false!"); if (arr && arr == false) console.log("...what??"); I guess this is due to the implicit conversion operated by the equality operator.(我猜这是由于相等运算符进行隐式转换所致。) Can anyone explain what's going on behind the scenes?(谁能解释幕后发生的事情?)   ask by Patonza translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're testing different things here.(您在这里测试不同的东西。)

if (arr) called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false.(if (arr)在对象(数组是JS中Object的实例if (arr)调用的if (arr)将检查该对象是否存在,并返回true / false。) When you call if (arr == false) you compare values of this object and the primitive false value.(调用if (arr == false) ,将比较此对象的和原始false值。) Internally, arr.toString() is called, which returns an empty string "" .(在内部,将调用arr.toString() ,它返回一个空字符串"" 。) This is because toString called on Array returns Array.join() , and empty string is one of falsy values in JavaScript.(这是因为在Array上调用的toString返回Array.join() ,而空字符串是JavaScript中虚假的值之一。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...