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 值至关重要。
以上就是未定义的情况的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号