简体   繁体   中英

Differences on these two 'isInArray' functions?

Which is more accurate/cross-browser compatible?

Example 1

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

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray


Example 2

function isInArray(arr,str) {
    return (arr.indexOf(str) != -1);
}

-I lost the source-

They do completely different things.

The first tests to see if something is an array. The second tests to see if an array contains a given object.

You are comparing apples and oranges.

The first function checks if the object is and array. The second function checks for a value in an array.

These functions do different things. The first tries to check if the variable is an array but the second checks if an element is in a given array. The first one also probably won't be that comparable cross browser just because it uses teh literal value '[object Array]' which will probably not be the same everywhere,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM