length
property.
{0: ' 1', 1: ' 2', 2: ' 3', length: 3};
__proto__
property.
DOMTokenList
NamedNodeMap
DOMStringMap
HTMLCollection
NodeList
HTMLAllCollection
StyleSheetList
DOMStringList
HTMLMapElement
CSSRuleList
length
property, which must be an integer and be greater than or equal to zero.
Number.isInteger(Number(object.length)) && Number(object.length) >= 0
undefined
Collection
, Map
or List
. But this idea was immediately dispelled, since a pseudo-array can be of the usual object type - Object
,
length
property is equal to a number that is greater than or equal to zero.
typeof object.length === 'number' && Number(object.length) >= 0
Array.from({0: ' 1', 1: ' 2', length: 1.6}); // [' 1'] Array.from({0: ' 1', 1: ' 2', 2: ' 3', length: 2.3}); // [' 1', ' 2']
var object = {0: 1, 1: 2, 2: 3, length: 3} var array = []; // for (var i = 0; i < object.length; i++) { array.push(object[i]); }; console.log( array ); // [1, 2, 3]
Array.from()
Function
var object = {0: 1, 1: 2, 2: 3, length: 3} // var array = Array.from(object); console.log( array ); // [1, 2, 3]
Array.prototype.slice.call()
( [].slice.call()
) [].slice.call()
var object = {0: 1, 1: 2, 2: 3, length: 3} // var array = Array.prototype.slice.call(object); // : [].slice.call(object); console.log( array ); // [1, 2, 3]
NodeList
( NodeList
, HTMLCollection
, etc.).
var object = document.querySelectorAll(selector); // var array = [...object]; console.log( array ); // [element, element, element]
__proto__
property
__proto__
object to Array.prototype
, then the pseudo-array is converted to an array. But this method is included in those “except for some cases” about which I wrote above, since, for a complete transformation into an array, the length
property must be an integer.
var object = {0: 'a', 1: 'b', 2: 'c', length: 3} // __proto__ object.__proto__ = Array.prototype; console.log(object); // ['a', 'b', 'c']
length
number, which will be less than the number of records in the pseudo-array, then we will have an array with the number of records specified in length
and with additional properties from the rest of the records.
var object = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', length: 3} // __proto__ object.__proto__ = Array.prototype; console.log(object); // ['a', 'b', 'c', 3: 'd', 4: 'e']
Array.isArray();
function Array.isArray();
.
var object = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', length: 3} // __proto__ object.__proto__ = Array.prototype; console.log( Array.isArray(object) ); // false
forEach
using forEach
or filter it with the filter
function. For such purposes, functions have an additional function .call()
, which makes it possible to work with pseudo-arrays.
var object = {0: 'a', 1: 'b', 2: 'c', length: 3} // object = Array.prototype.map.call(object, v => ': ' + v); // : [].map.call(object, v => ': ' + v) console.log(object); // [': a', ': b', ': c']
Source: https://habr.com/ru/post/336136/