您好,欢迎访问一九零五行业门户网

未定义的情况

javascript 以两种略有不同的方式使用 undefined 值。
它的第一种使用方式是指示声明的变量 (var foo) 没有分配值。第二种使用方式是指示您尝试访问的对象属性尚未定义(甚至还没有命名),并且在原型链中找不到。
在下面的示例中,我通过 javascript 检查了 undefined 的两种用法。
示例:sample62.html
<!doctype html><html lang=en><body><script> var initializedvariable; // declare variable. console.log(initializedvariable); // logs undefined. console.log(typeof initializedvariable); // confirm that javascript returns undefined. var foo = {}; console.log(foo.bar); // logs undefined, no bar property in foo object. console.log(typeof foo.bar); // confirm that javascript returns undefined.</script></body></html>
允许 javascript 单独使用 undefined 被认为是良好的做法。您永远不应该发现自己将值设置为 undefined,如 foo = undefined。相反,如果您指定属性或变量值不可用,则应使用 null。
未定义的变量与以前的版本不同,javascript ecma-262 edition 3(及更高版本)在全局范围内声明了一个名为 undefined 的全局变量。由于该变量已声明且未赋值,因此未定义的变量设置为 undefined。
示例:sample63.html
<!doctype html><html lang=en><body><script> // confirm that undefined is a property of the global scope. console.log(undefined in this); // logs true.</script></body></html>
结论在使用 javascript 时,充分理解 undefined 值至关重要。
以上就是未定义的情况的详细内容。
其它类似信息

推荐信息