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