今天我的一位朋友说:
if (typeof isoft == "undefined") var isoft = new Object();
是这样的代码是由新生写的并写
if(!isoft) var isoft = new Object();
我原本认为必须有一些区别。但我无法找到差异。是 有吗?或者这两个例子是一样的吗?
感谢。
答案 0 :(得分:2)
请参阅问题Javascript, check to see if a variable is an object,但请注意 Tom Ritter接受的答案似乎不完整,请查看对其答案的评论。另请参阅community answer by Rob。
答案 1 :(得分:1)
如果isoft
应该包含对象的引用,则两者都是相同的。对于所有错误值,!isoft
都为真,但对象不能为假值。
答案 2 :(得分:1)
在涉及您提供的常规对象的示例中,几乎没有区别。但是,另一种典型模式可能是:
var radioButtons = document.forms['formName'].elements['radioButtonName'];
if ('undefined' === typeof radioButtons.length) {
radioButtons = [ radioButtons ];
}
for (var i = 0; i < radioButtons.length; i++) {
// ...
}
如果你使用if (!radioButtons.length)
,当没有找到单选按钮(radioButtons.length为0)时,它将评估为true,并创建一个单独(不存在)单选按钮的数组。如果您选择使用以下方式处理单选按钮,则会出现同样的问题:
if ('undefined' === typeof radioButtons.length) {
// there is only one
} else {
// there are many or none
}
还有其他涉及空字符串的示例,其中可能不推荐使用if (!variable)
,最好针对未定义的类型进行测试,或者针对null进行显式测试。
答案 3 :(得分:1)
在您的特定示例中,没有显着差异,因为您正在评估Object实例,并且在转换为Boolean时对象将转换为Boolean true,而undefined和null将被计算为Boolean false。 但请以此为例:
function alertSomething(something) {
//say you wanna show alert only if something is defined.
//but you do not know if something is going to be an object or
//a string or a number, so you cannot just do
//if (!something) return;
//you have to check if something is defined
if (typeof something=='undefined') return;
alert(something);
}
我喜欢在任何地方使用快捷方式并保存打字,当然,但你必须知道何时采取快捷方式,何时不要;)