判断一个值的类型

1.直接使用typeof(不足:null 和 [ ] 和 { } 会都出现object)

console.log(typeof 666);  //number
console.log(typeof '666'); //string
console.log(typeof true);  //boolean
console.log(typeof undefined); //undefined
console.log(typeof null); //object
console.log(typeof []);  //object
console.log(typeof {}); //object
console.log(typeof function() {}); //function

2.使用instanceof和typeof结合

function getValueType(value) {
  var type = '';
  if (typeof value != 'object') {
    type = typeof value;
  } else {
    if (value instanceof Array) {
      type = 'array';
    } else {
      if (value instanceof Object) {
        type = 'object';
      } else {
        type = 'null';
      }
    }
  }
  return type;
}

 输出结果

getValueType(666);  //number
getValueType('666'); //string
getValueType(true);  //boolean
getValueType(undefined); //undefined
getValueType(null); //null
getValueType([]);   //array
getValueType({});  //object
getValueType(function(){}); //function

猜你喜欢

转载自www.cnblogs.com/wuaidongfang/p/10408385.html