如何检查JavaScript对象属性是否未定义

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值