Home > Web Front-end > JS Tutorial > body text

Introduction to the method of determining whether a variable is an object or an array in JavaScript

巴扎黑
Release: 2017-07-18 17:02:10
Original
1311 people have browsed it
  1. Because whether it is an array or an object, the return value of the typeof operation is object, so there is a need to distinguish between array types and object types:

  2. Fang 1: Through the length attribute: Generally, the object does not have a length attribute value, its value is undefiend, and the length value of the array is of type number

  3. Disadvantages: Very impractical, when the object The attribute of length exists and its value is number (such as array-like), then this method is invalid and is not recommended to be used. Just take a look.

  4. *Part 2: Judge the distinction through instanceof

  5. 1.instanceof

var arr = [1, 2, 3];
var obj = {
name: 'lyl',
age: 18,
l: 'name'
}
console.log(arr instanceof Array); //true
console.log(obj instanceof Array) ; //false

2.constructor

var arr = [1, 2, 3];
var obj = {
name: 'lyl',
age: 18,
1: 'name'
}
console.log(arr.constructor = == Array); //true
console.log(obj.constructor === Array); //false

3.Object.prototype.toString()

var arr = [1, 2, 3];
var obj = {
name: 'lyl',
age: 18,
1: 'name'
}
console.log(Object.prototype.toString.call(arr) === '[object Array]'); / /true
console.log(Object.prototype.toString.call(boj) === '[object Array]'); //false

4. Array only Methods (such as: sort, pop, etc.)

var arr = [1, 2, 3];
var obj = {
name: 'lyl ',
age: 18,
1: 'name'
}
console.log(arr.sort === Array.prototype.sort); //true
console.log(obj.sort === Array.prototype.sort); //false

The above is the detailed content of Introduction to the method of determining whether a variable is an object or an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template