Preface
In our daily development, we often need to judge a certain value type. Today we summarize several common JavaScript methods for judging whether it is an array.
Array.isArray
Array.isArray() is a new method of ES5, used to determine whether the passed value is an array, if it is an array, it returns true, otherwise it returns false.
let arr = [];
console.log(Array.isArray(arr)); // true
The following function calls all return true:
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
One thing to note is: In fact, Array.prototype is also an array.
Array.isArray(Array.prototype); // true
The following function calls all return false:
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32))
Array.isArray({ __proto__: Array.prototype });
The compatibility is as follows:
It can be seen that the new version of mainstream browsers support this method, and you can use it with confidence.
constructor
Each instance of Object has a constructor, which is used to store the functions used to create the current object
let arr = [];
console.log(arr.constructor === Array); // true
It should be noted that the constructor has the risk of being modified, and the judgment result may not be accurate, such as:
let arr = [1, 2, 3];
arr.constructor = function () { }
console.log(arr.constructor === Array); // false
It is generally not recommended to use the constructor to determine whether it is an array, we only need to know that there is such a method.
instanceof
The instanceof operator is used to detect whether the prototype property of the constructor appears on the prototype chain of an instance object. for example:
// 定义构造函数
function C() {}
function D() {}
var o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false,因为 D.prototype 不在 o 的原型链上
o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true
C.prototype instanceof Object; // true,同上
The usage of instanceof to determine whether it is an array is as follows:
let arr = [];
console.log(arr instanceof Array); // true
There are two points to note when using instanceof:
- Both the prototype of the constructor and the prototype chain of the instance may change, so the result of the judgment may not be static.
- Using instanceof in page scripts with iframes may get wrong results, because iframes have independent global environments, and different global environments have different global objects, and thus have different built-in type constructors.
isPrototypeOf
isPrototypeOf()
can be used to test whether an object exists in the prototype chain of another object. The usage is as follows:
function Foo() {}
function Bar() {}
function Baz() {}
Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);
var baz = new Baz();
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
If you want to use isPrototypeOf to determine whether the incoming parameter is an array, you can use it like this:
let arr = [];
console.log(Array.prototype.isPrototypeOf(arr)); // true
Object.prototype.toString
Each object has a toString()
method, which is automatically called when the object is represented as a text value, or when an object is referenced in an expected string manner.
By default, the toString()
method is Object object. If this method is not covered in the custom object, toString()
returns the [object type] ", where type is the type of the object.
You can get the type of each object toString()
In order for each object to be detected by Object.prototype.toString(), it needs to Function.prototype.call()
or Function.prototype.apply()
, passing the object to be checked as the first parameter, called thisArg. The usage is as follows:
var toString = Object.prototype.toString;
toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
If you want to determine whether an object is an array, you can use it like this:
let arr = [];
console.log(Object.prototype.toString.call(arr) === "[object Array]"); // true
The compatibility is as follows:
typeof
When it comes to judging the type, many people may think of the typeof method. Let's review the content of typeof here.
The typeof operator returns a string that represents the type of the unevaluated operand.
console.log(typeof 42); // "number"
console.log(typeof 'blubber'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undeclaredVariable); // "undefined"
The possible return values of typeof are as follows:
As you can see from the above figure, the array object belongs to "any other object", so the typeof return value of the array object is "object":
let arr = [];
console.log(typeof arr); // "object"
Therefore, we should try to avoid using typeof.
Summarize
The above are several ways to determine whether a value is an array. Of course there are some useful and some not, but anyway, we know that it is always good to have such a thing. in conclusion:
- The best method is
Array.isArray
, but IE8 and below are not supported. - If you want to consider compatibility, you can use
Object.prototype.toString
.
~
~ End of this article, thanks for reading!
~
Learn interesting knowledge, meet interesting friends, and create interesting souls!
Hello everyone, I am , the author Programming Samadhi Hermit King , and my is "1612a567fcd59c Programming Samadhi ", welcome to pay attention, I hope you can give me your advice!
Come, with expectations, I have Moxiang to greet you! You return, no matter the gains or losses, only with the lingering rhyme as a gift!
Pay equal attention to knowledge and skills, both internal and external skills, both theory and practice must be grasped, and both hands must be hard!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。