检验一个变量是数组或字符串

一、检验一个变量是String类型

typeof(str) === 'string'
typeof str === 'string'
str.constructor === String

Note: 如果用typeof来判断一个变量是否存在,需要使用:

if(typeof a!="undefined"){alert("ok")}

不要使用

if(a)

因为吐过a没有声明,不存在,就会出错

二、检验一个变量是数组

1、instanceof

function isArray (obj) {
  return obj instanceof Array;
}

2、Array.isArray

function isArray (obj) {
  return Array.isArray(obj);
}

3、Object.prototype.toString

function isArray (obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

 

posted @ 2018-11-13 16:13  maomao^_^  阅读(740)  评论(0编辑  收藏  举报