JavaScript pseudo-arrays and conversions to standard arrays

Source: Internet
Author: User

1: What is a pseudo-array

A pseudo-array is a JSON object that contains the length property.

It stores the data as an index,

It does not have some methods of arrays, only can be converted through Array.prototype.slice to real arrays, and objects with the length property.

    var obj = {0: ' A ', 1: ' B ', length:2}; Pseudo    -array var arr = Array.prototype.slice.call (obj);//Convert to array        console.log (arr);  return ["A", "B"]

2: Its and array relationships

It's all analog collections.

3: Why there are pseudo-arrays

In daily development, many objects are made up of pseudo-arrays, such as arguments objects within functions, as well as calls to Getelementsbytagname,document.childnodes, which all return nodelist objects are pseudo-arrays.

4: Why use the Array.prototype.slice.call () method to convert a pseudo-array to an array

In fact, we can achieve the same effect by [].slice.call], but it is more efficient to execute the program in the form of prototype, and the same code is more graceful.

This is the V8 engine in the array.js to the slice side of the implementation process, interested students can study.

I understand the idea is ↓, may not be, for reference only.

12345678 functionslice(obj) {    vararr =[];    varlen = obj.length; // length 正好对应伪数组中的length属性    for(vari = 0;i < len;i++){        arr.push[i] = obj[i]; // i 正好对应伪数组中的索引值    }    returnarr;}

 

5:jquery and pseudo-arrays

In fact, jquery uses a lot of pseudo-arrays inside. It can be said that the entire jquery object is built on the basis of a pseudo-array.

JavaScript pseudo-arrays and conversions to standard arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.