注意:根据,window.undefined是只读的。
中更改
当我最近将Facebook Connect与Tersus集成时,我最初在尝试调用Facebook API函数时收到错误消息Invalid Enumeration Value
和Handler already exists
。
原来,问题的原因是
object.x === undefined
当'object‘中没有属性'x’时返回false。
我通过在两个Facebook函数中将严格相等替换为常规相等来解决此问题:
FB.Sys.isUndefined = function(o) { return o == undefined;};
FB.Sys.containsKey = function(d, key) { return d[key] != undefined;};
这让事情变得对我有用,但似乎暗示着Facebook的JavaScript代码和我自己的代码之间存在某种冲突。
是什么导致了这种情况?
提示:有很好的文档说明,在undefined !== null
的同时使用undefined == null
。这不是这里的问题。问题是我们是如何得到undefined !== undefined
的。
发布于 2009-04-26 10:39:36
事实证明,您可以将window.undefined设置为您想要的任何值,因此,当object.x是真正未定义的对象时,您可以获得object.x !== undefined
。在我的例子中,我无意中将undefined设置为null。
实现这一点的最简单方法是:
window.undefined = null;
alert(window.xyzw === undefined); // shows false
当然,这不太可能发生。在我的例子中,bug更加微妙,相当于下面的场景。
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
发布于 2009-04-22 13:28:48
问题是,使用==将未定义的值与null进行比较会得到true。因此,对undefined的通用检查如下所示:
typeof x == "undefined"
这确保了变量的类型是真正未定义的。
发布于 2011-07-03 01:33:28
我想发布一些初学者可能不知道的关于undefined
的重要信息。
请看下面的代码:
/*
* Consider there is no code above.
* The browser runs these lines only.
*/
// var a;
// --- commented out to point that we've forgotten to declare `a` variable
if ( a === undefined ) {
alert('Not defined');
} else {
alert('Defined: ' + a);
}
alert('Doing important job below');
如果您运行这段代码,其中变量a
从未使用var
声明过,您将得到一个错误异常,并且意外地看不到任何警告。
你的脚本不会“在下面做重要的工作”,而是会意外终止,在第一行抛出未处理的异常。
这是使用typeof
关键字检查undefined
的唯一有效方法,它就是为此目的而设计的:
/*
* Correct and safe way of checking for `undefined`:
*/
if ( typeof a === 'undefined' ) {
alert(
'The variable is not declared in this scope, \n' +
'or you are pointing to unexisting property, \n' +
'or no value has been set yet to the variable, \n' +
'or the value set was `undefined`. \n' +
'(two last cases are equivalent, don\'t worry if it blows out your mind.'
);
}
/*
* Use `typeof` for checking things like that
*/
此方法适用于所有可能的情况。
使用它的最后一个论点是,undefined
可能会在早期版本的Javascript中被覆盖:
/* @ Trollface @ */
undefined = 2;
/* Happy debuging! */
希望我说得够清楚了。
https://stackoverflow.com/questions/776950
复制相似问题