JS four methods of detecting array

Today and share with you four methods of detection is not an array of JS, although not long, but a more comprehensive approach should be considered.

1. instanceof method

instanceof for detecting whether an object is an instance of a class it is also an array of objects it is also possible to use instaceof judgment.

let arr = [1, 2, 3];
console.log(arr.instanceof(Array)); // true

In this way only a global scope environment is possible, but if a page contains a plurality of frames, it will have a different global environment, different environments Array constructor is different, so the two there will be a problem when passing an array frame, detected in a framework of an array, but the array is not detected in another frame.

2. Array.isArray method

isArray method for determining a value in the end is not an array, regardless of what is in the environment are possible. But this method is a low version of the IE browser is not supported.

let arr = [1, 2, 3];
console.log(Array.isArray(arr));

3. Array constructor

When you create an array can be used let arr = new Array()in the form of, in turn, we can use constructor property to get its constructor is not based on Array to determine a value is not an array.

let arr = [1, 2, 3];
console.log(arr.constructor === Array) // true

This method and the method has the same drawbacks in multiple environments Array constructor might be different, but the problem is likely to occur if you want to pass an array of words in multiple environments.

4. Object.prototype.toString.call () method

We know, Object native toString method call on any value, will return [object NativeConstructorName] format string may also be used to take advantage of this testing is not an array.

let arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr) === "[object Array]"); // true

Since the constructor name has nothing to do with the global environment native array, so this method can detect an array of right no matter under which conditions.

Note: Array of Method 1 and Method 3 are the properties window.

Finished, if impropriety please correct me oh.

Guess you like

Origin www.cnblogs.com/zhangguicheng/p/12178034.html