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

王林
Release: 2020-03-13 10:25:23
forward
5860 people have browsed it

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';
Copy after login

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
Copy after login

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
Copy after login

5. Array.isArray()

Array.isArray([])  // true
Copy after login

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!

Related labels:
source:jb51.net
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