在javascript中工作時,有人可以爲我提供一個很好的參考或解釋測試相等/不等式和類型強制嗎?JavaScript中的平等
從我一直在閱讀中,我看到在使用eqeq(==)和eqeqeq(===)時有兩個思想原理,有些人覺得你不應該使用eqeq,並總是使用eqeqeq,因爲它是使用更安全。
我一直在玩弄一些基本的樣品,我無法辨別的差異,或當最好使用一個比其他:
例如:這裏是一些基本的腳本我寫出來。當我使用eqeq或eqeqeq進行測試時,我會得到相同的結果。我還沒有看到一個例子,但我會得到不同的結果(即,使用eqeq返回true,其中eqeqeq返回false)。
function write(message){
document.getElementById('message').innerHTML += message +'<br/>';
}
var tim = { name: "tim" };
var tim2 = { name: "tim" };
//objects are equal to themselves (== vs ==== eqeq or eqeqeq)
write("tim eq tim: " + (tim == tim)); //returns true
//objects are only equal to themselves regardless of containing value got that
write("tim eq tim2: " + (tim === tim2)); //returns false
//access the primative type to test true or false
write("tim value eq tim2 value: " + (tim.name === tim2.name)); //returns true
//how does this differ in efficency over the eqeq operator? is one safer to use over the other?
//write("tim value eq tim2 value: " + (tim.name == tim2.name)); //also returns true
//testing primatives
write("apple eqeqeq apple: " + ("apple" === "apple")); //true
write("apple eqeqeq apple: " + ("apple" == "apple")); //true
有人可以提供一個解釋或參考我可以閱讀,有助於澄清這一點。
歡呼聲,
http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – 2012-03-17 15:10:22