美文网首页
js数据类型判断和数组判断

js数据类型判断和数组判断

作者: passerbyli | 来源:发表于2017-02-20 08:13 被阅读59次

JS六大基本类型:number,String,object,Boolean,null, undefined

数据类型判断 typeof

只能判断number,String,boolean, undefined。其余的全部返回Object类型。

数组判断

  1. instanceof 判断对象必须事先声明
var a = [1,2,3];
consosle.log(a instanceof Array);
  1. constructor 返回对创建此对象的函数的引用. 判断对象必须事先声明
  var a = [1,2,3];
  console.log(a.constructor == Array);//true or false

  console.log([].constructor == Array);
  console.log({}.constructor == Object);
  console.log("string".constructor == String);
  console.log((123).constructor == Number);
  console.log(true.constructor == Boolean);

  //严谨判断方法
  function isArray(object){
    return object  && typeof object ==='object' && Array == object.constructor
  }
  1. 特性判断法
    object. propertyIsEnumerable(proName)
    判断指定的属性是否可列举
    备注:如果 proName 存在于 object 中且可以使用一个 For…In 循环穷举出来,那么 propertyIsEnumerable 属性返回 true。如果 object 不具有所指定的属性或者所指定的属性不是可列举的,那么 propertyIsEnumerable 属性返回 false。
    propertyIsEnumerable 属性不考虑原型链中的对象。
    eg:
var a = new Array("apple", "banana", "cactus");
document.write(a.propertyIsEnumerable(1));
  1. 最简单判断方法
function isArray(o) {
    return Object.prototype.toString.call(o) === ‘[object Array]‘;
}

完整类型判断方法

function typeOf(value) {
    if (null === value) {
        return 'null';
    }

    var type = typeof value;
    if ('undefined' === type || 'string' === type) {
        return type;
    }

    var typeString = Object.prototype.toString.call(value);
    switch (typeString) {
    case '[object Array]':
        return 'array';
    case '[object Date]':
        return 'date';
    case '[object Boolean]':
        return 'boolean';
    case '[object Number]':
        return 'number';
    case '[object Function]':
        return 'function';
    case '[object RegExp]':
        return 'regexp';
    case '[object Object]':
        if (undefined !== value.nodeType) {
            if (3 == value.nodeType) {
                return (/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';
            } else {
                return 'element';
            }
        } else {
            return 'object';
        }
    default:
        return 'unknow';
    }
}

文章摘抄:
js数据类型判断和数组判断
通过 Object.prototype.toString.call() 进行类型判断

相关文章

网友评论

      本文标题:js数据类型判断和数组判断

      本文链接:https://www.haomeiwen.com/subject/rbityttx.html