typeof运算符_JavaScript typeof运算子

本文深入探讨了JavaScript中的typeof运算符,解释了如何使用它来确定变量的类型,包括基本类型如number、string、boolean,以及复杂类型如object、function和symbol。文章还讨论了未初始化变量的默认undefined类型,以及typeof在对象属性检测中的应用。

typeof运算符

In JavaScript, any value has a type assigned.

在JavaScript中,任何值都有分配的类型。

The typeof operator is a unary operator that returns a string representing the type of a variable.

typeof运算符是一元运算符,它返回表示变量类型的字符串。

Example usage:

用法示例:

typeof 1 //'number'
typeof '1' //'string'
typeof {name: 'Flavio'} //'object'
typeof [1, 2, 3] //'object'
typeof true //'boolean'
typeof undefined //'undefined'
typeof (() => {}) //'function'
typeof Symbol() //'symbol'

JavaScript has no “function” type, and it seems funny that typeof returns 'function' when we pass it a function.

JavaScript没有“函数”类型,当我们将其传递给函数时, typeof返回'function'似乎很有趣。

It’s one quirk of it, to make our job easier.

这是一个怪癖,使我们的工作更轻松。

If you don’t initialize the variable when you declare it, it will have the undefined value until you assign a value to it.

如果在声明变量时未对其进行初始化,则该变量将具有undefined值,直到您为其分配值为止。

let a //typeof a === 'undefined'

typeof works also on object properties.

typeof也适用于对象属性。

If 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/javascript-typeof-operator/

typeof运算符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值