js类型判断1: typeof 和 判断array 以及是Array还是Object或者null

转载: https://blog.csdn.net/u013362969/article/details/81141945

typeof 返回值有六种可能: "number," "string," "boolean," "object," "function" ,"undefined."以及'symbol' 。

  1. // Symbols

  2. typeof Symbol() === 'symbol'

  3. typeof Symbol('foo') === 'symbol'

  4. typeof Symbol.iterator === 'symbol'

null,array,object返回的都是‘object’

1.instanceof
var arr = [1,2,3,1];
alert(arr instanceof Array); // true 

2、constructor

var arr = [1,2,3,1];
alert(arr.constructor === Array); // true 

第1种和第2种方法貌似无懈可击,但是实际上还是有些漏洞的,当你在多个frame中来回穿梭的时候,这两种方法就亚历山大了。由于每个iframe都有一套自己的执行环境,跨frame实例化的对象彼此是不共享原型链的,因此导致上述检测代码失效

3、Object.prototype.toString

function isArrayFn (o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
var arr = [1,2,3,1];
alert(isArrayFn(arr));// true 

4、Array.isArray()   【ie8 不支持】

5、综合

var arr = [1,2,3,1];
var arr2 = [{ abac : 1, abc : 2 }];
function isArrayFn(value){
if (typeof Array.isArray === "function") {
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value) === "[object Array]";
}
}
alert(isArrayFn(arr));// true
alert(isArrayFn(arr2));// true

-----------------------------

二、判断是Array还是Object或者null

利用typeof

  1. var getDataType = function(o){

  2. if(o===null){

  3. return 'null';

  4. }

  5. else if(typeof o == 'object'){

  6. if( typeof o.length == 'number' ){

  7. return 'Array';

  8. }else{

  9. return 'Object';

  10. }

  11. }else{

  12. return 'param is no object type';

  13. }

  14. };

或者用instanceof

  1. var getDataType = function(o){

  2. if(o===null){

  3. return 'null';

  4. }

  5. if(o instanceof Array){

  6. return 'Array'

  7. }else if( o instanceof Object ){

  8. return 'Object';

  9. }else{

  10. return 'param is no object type';

  11. }

  12. };

猜你喜欢

转载自blog.csdn.net/qq_38719039/article/details/81979345