在 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
有人可以提供我可以阅读的解释或参考,以帮助进一步澄清这一点。
cheers,
== 和 === 之间的区别非常简单:== 是值的比较。 === 是值和类型的比较。使用 === 将阻止 JavaScript 动态确定类型并按原样比较值。
5 == "5" //true - JS compares the number 5 to a string of "5" and determines the contents are the same
5 === "5" //false - A character is not a number, they can't be the same.
0 == false //true - false is a bool, 0 is numerical, but JS determines that 0 evaluates to false
0 === false //false - numeric is not boolean, they can't be exactly the same thing
5 == 5.0 //true - need I say more?
5 === 5.0 //true - one is a float and one is an int, but JS treats them all as numerical
我发现这对于使用可以返回 false(失败)和 0(作为合法结果)的函数的测试至关重要。
JS 共有 5 种基本类型:数值型、字符串型、布尔型、空型和未定义型。 === 要求两个参数的类型相同and相等的值返回true。没有 float、int、long、short 等——任何类型的数字都集中在一起作为数值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)