参考错误:引用未定义的属性 "x"
当脚本尝试访问不存在的对象属性时,会出现 JavaScript 警告 "对未定义属性的引用"。
¥The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.
信息
错误类型
¥Error type
(仅限 Firefox)仅当 javascript.options.strict
首选项设置为 true
时才会报告 ReferenceError
警告。
¥(Firefox only) ReferenceError
warning which is reported only if
javascript.options.strict
preference is set to true
.
什么地方出了错?
¥What went wrong?
该脚本尝试访问不存在的对象属性。有两种方法可以访问属性;请参阅 属性访问器 参考页以了解有关它们的更多信息。
¥The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them.
示例
无效案例
有效案例
¥Valid cases
为了避免该错误,你需要将 bar
的定义添加到对象中,或者在尝试访问它之前检查 bar
属性是否存在;方法包括使用 in
运算符或 Object.hasOwn()
方法,如下所示:
¥To avoid the error, you need to either add a definition for bar
to the
object or check for the existence of the bar
property before trying to
access it; ways to do that include using the in
operator,
or the Object.hasOwn()
method, like this:
const foo = {};
// Define the bar property
foo.bar = "moon";
console.log(foo.bar); // "moon"
// Test to be sure bar exists before accessing it
if (Object.hasOwn(foo, "bar")) {
console.log(foo.bar);
}
也可以看看
¥See also