判断数据类型(typeof)

  • 原文MDN - typeof

  • 功能typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

  • 方法typeof operand 或者 typeof(operand)

    • operand:一个表示对象或原始值的表达式,其类型将被返回。
  • 说明

下面列举下 typeof 可能的返回值:

类型 结果
Undefined ‘undefined’
Null ‘object’
Boolean ‘boolead’
Number ‘number’
BigInt ‘bigint’
String ‘string’
Symbol ‘symbol’
Function ‘function’
其他任何对象 ‘object’
  • 代码
/**
 * @name typeof测试
 * @description 通过 typeof 检测各个数据类型的返回
 */
const test = {
    
    
  testUndefined: undefined,
  testNull: null,
  testBoolean: true,
  testNumber: 123,
  testBigInt: BigInt(1234), // 大于 2 的 53 次方算 BigInt
  testString: '123',
  testSymbol: Symbol(),
  testFunction: function() {
    
    
    console.log('function');
  },
  testObject: {
    
    
    obj: 'yes',
  },
  testObjectString: new String('String'),
  testObjectNumber: new Number(123),
}

console.log(typeof(test.testUndefined)); // undefined
console.log(typeof(test.testNull));      // object
console.log(typeof(test.testBoolean));   // boolean
console.log(typeof(test.testNumber));    // number
console.log(typeof(test.testBigInt));    // bigint
console.log(typeof(test.testString));    // string
console.log(typeof(test.testSymbol));    // symbol
console.log(typeof(test.testFunction));  // function
console.log(typeof(test.testObject));    // object
console.log(typeof(test.testObjectString));    // object
console.log(typeof(test.testObjectNumber));    // object

猜你喜欢

转载自blog.csdn.net/weixin_43956521/article/details/111470200