Home >Web Front-end >JS Tutorial >How to determine whether an object is an array (function) in js

How to determine whether an object is an array (function) in js

王林
王林forward
2020-03-13 10:25:235859browse

How to determine whether an object is an array (function) in js

1. Typeof operator

Example:

// 数值
typeof 37 === 'number';
  
// 字符串
typeof '' === 'string';
  
// 布尔值
typeof true === 'boolean';
  
// Symbols
typeof Symbol() === 'symbol';
  
// Undefined
typeof undefined === 'undefined';
  
// 对象
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
  
// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
  
// 函数
typeof function() {} === 'function';

From the above example we can see that using typeof except array and null is judged as object Except for this, everything else can be judged normally.

(Recommended tutorial: javascript tutorial)

2. instanceof operator and constructor attribute of object

This operator is somewhat similar to object-oriented in JavaScript Relationship, to understand this, you must first understand object-oriented in JavaScript. Because this operator detects whether the prototype chain of the object points to the prototype object of the constructor.

Example:

How to determine whether an object is an array (function) in js

3. Use Object.prototype.toString to determine whether it is a number

Object.prototype.toString.call( [] ) === '[object Array]' // true
  
Object.prototype.toString.call( function(){} ) === '[object Function]' // true

Use call here Make this in toString point to obj. Then complete the judgment

4. Use the prototype chain to complete the judgment

[].__proto__ === Array.prototype // true
  
var fun = function(){}
fun.__proto__ === Function.prototype // true

5. Array.isArray()

Array.isArray([])  // true

ECMAScript5 officially introduces Array.isArray() into JavaScript for the purpose It is to accurately detect whether a value is an array. IE9, Firefox 4, Safari 5, Opera 10.5 and Chrome all implement this method. However, versions before IE8 are not supported.

Recommended related video tutorials: javascript video tutorial

The above is the detailed content of How to determine whether an object is an array (function) in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete