The use and difference between JavaScript pseudo-array and array

The use and difference between JavaScript pseudo-array and array

Pseudo-arrays and arrays

In JavaScript, except for the five primitive data types, all others are objects, including functions.

The relationship between objects and arrays

Before talking about the difference, we need to mention another piece of knowledge, which is JavaScript's prototype inheritance.

All JavaScript's built-in constructors inherit from Object.prototype.

Under this premise, it can be understood that array objects created using new Array() or [] will have the property values ​​of Object.prototype.

var obj = {}; // has the property value of Object.prototype var arr = [];
//Array created using array literals, because the properties of Array.prototype are inherited from Object.prototype,
//Then, it will have the property values ​​of both Array.prototype and Object.prototype

We can see the first difference between objects and arrays: objects do not have the property values ​​of arrays Array.prototype.

What is an array

Arrays have a basic feature: index, which objects do not have. Let's look at a piece of code:

var obj = {};
var arr = [];
 
obj[2] = 'a';
arr[2] = 'a';
 
console.log(obj[2]); // => a
console.log(arr[2]); // => a
console.log(obj.length); // => undefined
console.log(arr.length); // => 3
  • obj[2] outputs 'a' because objects are ordinary key-value pairs for accessing data.
  • However, arr[2] outputs 'a'. Arrays store and access data by index. The reason why arr[2] outputs 'a' is because the data is already stored at index 2 of the array arr.
  • obj.length does not have the characteristics of an array, and obj does not save the attribute length, so it will naturally output undefined
  • For arrays, length is a built-in property of the array, and the array will change the value of length according to the index length.
  • Why does arr.length output 3 instead of 1?
    • When adding elements to an array, they are not added according to consecutive indexes, so the index of the array is discontinuous, which causes the index length to be greater than the number of elements.

What is a pseudo array?

  1. Has a length property, and other properties (indexes) are non-negative integers (the index in the object will be treated as a string, so you can understand it as a string of non-negative integers)
  2. Does not have the methods that arrays have

A pseudo-array is an object that has a length attribute like an array, and also has attributes such as 0, 1, 2, 3, etc. It looks like an array, but it is not an array. For example:

var fakeArray = {
  "0": "first",
  "1": "second",
  "2": "third",
  length: 3
};
 
for (var i = 0; i < fakeArray.length; i++) {
  console.log(fakeArray[i]);
}
 
Array.prototype.join.call(fakeArray,'+');

Common pseudo-arrays are:

  • Arguments inside a function
  • A list of DOM objects (such as the list obtained by document.getElementsByTags)
  • jQuery objects (e.g. $("div") )

A pseudo-array is an Object, while a real array is an Array.

The purpose of pseudo-arrays is to allow ordinary objects to use many methods of arrays normally, such as:

var arr = Array.prototype.slice.call(arguments);
 
Array.prototype.forEach.call(arguments, function(v) {
  // loop over arguments object });

// push
//some
// every
// filter
// map
// ...

The above can be simplified by using array literals when borrowing array prototype methods:

var obj = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
}

;[].push.call(obj, 'd')

console.log([].slice.call(obj))

;[].forEach.call(obj, function (num, index) {
  console.log(num)
})

The difference between the two

1. Length:

  • True arrays are variable length
  • The length of the pseudo-array is immutable

2. Use of the method:

  • True arrays can use array methods
  • Pseudo-arrays cannot use array methods

summary

Objects do not have an array property value. The type of the prototype is Object, while the type of the array is Array.
Arrays are implemented based on indexes, length is automatically updated, and objects are key-value pairs. Using objects, you can create pseudo-arrays, and pseudo-arrays can use most of the methods of arrays normally.

Summarize

This is the end of this article about the usage and differences of JavaScript pseudo-arrays and arrays. For more relevant JavaScript pseudo-array and array content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Code to convert HTMLCollection/NodeList/pseudo array into array in js
  • JavaScript pseudo array implementation method
  • Example Analysis of JavaScript Pseudo-Array Usage
  • JS Array.from() method example to convert a pseudo-array into an array

<<:  How to add java startup command to tomcat service

>>:  Detailed tutorial on installing Nginx 1.16.0 under Linux

Recommend

How to define data examples in Vue

Preface In the development process, defining vari...

Detailed explanation of HTML page header code example

Knowledge point 1: Set the base URL of the web pa...

Notes on configuring multiple proxies using vue projects

In the development process of Vue project, for th...

Detailed explanation of various types of image formats such as JPG, GIF and PNG

Everyone knows that images on web pages are genera...

MySQL database backup and recovery implementation code

Database backup #grammar: # mysqldump -h server-u...

MySQL 8.0.12 Installation and Configuration Tutorial

This article records the detailed tutorial for in...

Use non-root users to execute script operations in docker containers

After the application is containerized, when the ...

How to install nginx on win10

Because the company asked me to build a WebServic...

CSS method of controlling element height from bottom to top and from top to bottom

Let’s start the discussion from a common question...

Detailed explanation of 6 ways of js inheritance

Prototype chain inheritance Prototype inheritance...

MySQL compression usage scenarios and solutions

Introduction Describes the use cases and solution...

How to solve the problem of case insensitivity in MySQL queries

question Recently, when I was completing a practi...

CSS animation property usage and example code (transition/transform/animation)

During development, a good user interface will al...

MySQL 8.0.20 winx64 installation and configuration method graphic tutorial

This article shares with you the installation and...