This article mainly introduces three methods for determining whether JavaScript is an array and compares the efficiency. This article provides the running effect and implementation code, for more information about the efficiency of chrome, see the following comparison of different array determination methods:
The code is as follows:
Var ret; var o = [1, 2, 3]; var toStr = {}. toString; var array ={}; array ["[object Array]"] = "array"; console. log ("various speed comparisons to determine whether an array is used! ") Console. log ("Method 1: Array. isArray (o) "); console. time ("first"); for (var I = 0; I <10000; I ++) {ret = Array. isArray (o);} console. timeEnd ("first"); console. log (ret); console. log ("Method 2: o instanceof Array"); console. time ("second"); for (var I = 0; I <10000; I ++) {ret = o instanceof Array;} console. timeEnd ("second"); console. log (ret); console. log ("method 3: o. constructor = Array "); console. time ("thirth"); for (var I = 0; I <10000; I ++) {ret = o. constructor = Array;} console. timeEnd ("thirth"); console. log (ret); console. log ("method 4: array [toStr. call (o)] = 'array' "); console. time ("forth"); for (var I = 0; I <10000; I ++) {ret = array [toStr. call (o)] = "array";} console. timeEnd ("forth"); console. log (ret );