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

1264

被折叠的 条评论
为什么被折叠?



