1. Frequently encountered problems:
When judging the type of an object in JS, typeof is usually used. At this time, the problem arises, because typeof() returns when identifying an array. object, so judging whether an object is an array in JS
requires some special processing methods. The six processing methods summarized by me are introduced below.
2. Straight to the point
To determine whether an object is an array during development, it is recommended to use the following function:
function isArray(obj){ if(Array.isArray){ return Array.isArray(obj); }else{ return Object.prototype.toString.call(obj)==="[object Array]"; } }
The above function is convenient for people who are eager to solve problems. I will describe the six methods in detail below, because the examiner may need a comprehensive knowledge of you during the interview;
3. Detailed explanation of the six solutions:
(1) Method 1: Use the toString method
Try to convert the variable into a string representing its type by calling the toString() method. This method is feasible for real arrays; when the parameter object is converted to string
returns [object Arguments], the conversion will fail; in addition, the conversion will also fail for the object class containing a numeric length attribute.
The method is as follows:
nbsp;html> <title>Array的判断方法</title> <meta> <script> function isArrayOne(arr){ return <span style="color:#cc0000;">Object.prototype.toString.call(arr) === "[object Array]"; } var obj = {"k1":"v1"}; var arr = [1,2]; console.log("对象的结果:"+isArrayOne(obj)); console.log("数组的结果:"+isArrayOne(arr)); </script>
The result is as shown:
Note: It is recommended to use "===" for equals instead of "==" for equals, because it is more efficient!
(2) Method 2: Through isArray:
Using Javascript 1.8.5 (ECMAScript 5), the variable name .isArray() can achieve this purpose, provided that this function is supported. In fact, isArray is the encapsulation of
method one.
The usage is very simple:
Array.isArray(obj); //obj is the object to be detected
Returns true or false, if true, it is an array
(3) Method 3: Judge through the instanceof operator,
Note: The left side of the instanceof operator is the child object (the object to be tested), and the right side is the parent constructor (here is Array),
That is: child object instanceof parent constructor
instance: instance: any object created with new constructor () is called an instance of the constructor
I’ve been confused for a long time, so it’s better to look at the code directly:
nbsp;html> <meta> <meta> <meta> <meta> <meta> <title>Document</title> <script> var obj = {"k1":"v1"}; var arr = [1,2]; console.log("Instanceof处理对象的结果:"+(obj instanceof Array)); console.log("Instanceof处理数组的结果:"+(arr instanceof Array)); </script>
The running results are as follows:
(4) Use the isPrototypeOf() function
Principle: Detect whether an object is the prototype of Array (or is in the prototype chain, not only the direct parent object, but also all parent objects on the entire prototype chain can be detected)
Usage: parent.isPrototypeOf(child) to detect whether parent is the prototype of child;
It should be noted that the function implemented by the isPrototypeOf() function is very similar to the instancof operator;
Specific code:
Array.prototype.isPrototypeOf(arr) //true means it is an array, false means it is not an array
(5)Use the constructor
Specific code:
nbsp;html> <meta> <meta> <meta> <meta> <meta> <title>Document</title> <script> var obj = {'k':'v'}; var t1 = new Array(1); var t2 = t1; console.log(obj.constructor == Array); console.log(t1.constructor == Array); console.log(t2.constructor == Array); </script>
The result is as shown in the figure
(6) Use typeof(object ) + type name combined judgment:
The code is as follows:
nbsp;html> <meta> <meta> <meta> <meta> <meta> <title>Document</title> <script> function isArrayFour(arr){ if(typeof(arr)==="object"){ if(arr.concat){ return "This is Array"; }else{ return "This Not Array"; } } } var arr = [1]; var obj = {'k':'v'}; console.log(typeof(arr)); console.log(typeof(obj)); console.log(isArrayFour(arr)); console.log(isArrayFour(obj)); </script>
The result is as follows:
This method actually has limitations Sex, some students may crack it at once, that is, what if
What if this attribute is accidentally defined in the object
var obj = {'concat':'Teast me?'};
The above summary of the six methods of distinguishing Object and Aarry in JS is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.
For more articles related to the summary of the JS method of distinguishing Object and Aarry, please pay attention to the PHP Chinese website!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment