In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof
operator.
在JavaScript程序中,检查对象属性是否未定义的正确方法是使用typeof
运算符。
typeof
returns a string that tells the type of the operand. It is used without parentheses, passing it any value you want to check:
typeof
返回一个字符串,该字符串告诉操作数的类型。 它不带括号使用,将要检查的任何值传递给它:
const list = []
const count = 2
typeof list //"object"
typeof count //"number"
typeof "test" //"string"
typeof color //"undefined"
If the value is not defined, typeof
returns the ‘undefined’ string.
如果未定义值,则typeof
返回'undefined' 字符串 。
Now suppose you have a car
object, with just one property:
现在假设您有一个只有一个属性的car
对象:
const car = {
model : 'Fiesta'
}
This is how you check if the color
property is defined on this object:
这是检查color
属性是否在此对象上定义的方法:
if ( typeof car . color === 'undefined' ) {
// color is undefined
}
翻译自: https://flaviocopes.com/how-to-check-undefined-property-javascript/