本文共 1212 字,大约阅读时间需要 4 分钟。
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运算符
转载地址:http://pvqgb.baihongyu.com/