This article mainly introduces some methods of converting JS from non-array objects to arrays, namely Array.prototype.slice.call(obj), Array.from(obj), [...obj] and Object.values( obj) and other methods, friends in need can refer to it, I hope it can help everyone.
Array.prototype.slice.call(obj)
This method can convert an array-like object into an array, the so-called class An array object is an object containing length and index properties.
The returned array length depends on the value of the object's length property, and the value of a non-index property, or a value with an index greater than length will not be returned to the array.
The actual hammer is as follows
let obj = { '0': 3, '1': 13, '2': 23, '3': 33, 'length': 3, 'name': 330 } let arr = Array.prototype.slice.call(obj) // [3, 13, 23]
Concise writing method[].slice.call(obj)
##Array.from(obj )
document.getElementsByTagName(" p") Returns an iterable object but not an array
Array.isArray(document.getElementsByTagName('p')) Returns false
let obj = { '0': 3, '1': 13, '2': 23, '3': 33 } function *createIterator(obj){ for(let value in obj){ yield obj[value] } } let iterator = createIterator(obj) let arr = Array.from(iterator) // [3, 13, 23, 33]
Symbol.iterator property, you can turn it into an iterable object
let obj = { '0': 3, '1': 13, '2': 23, '3': 33 } obj[Symbol.iterator] = function* () { for(let value in this){ yield this[value] } } let arr = Array.from(obj) // [3, 13, 23, 33]
typeof obj[Symbol.iterator] === 'function'
hasOwnProperty() method to determine whether the property is the object's own property
Object.getOwnPropertyNames(obj) , returns the enumerable or non-enumerable properties of the object itself
Object.assign() Method copies the values of all enumerable properties from one or more source objects to the target object
[…obj]
[...'obj'] Returns
["o", "b", "j "]
[...new Set('objobj')]
Object.values(obj)
Unlike array-like objects that require objects to have length values,
Object.values(obj)Returns the enumerable property values of the object itself Collection
let obj = { '0': 3, '1': 13, '2': 23, '3': 33 } let arr = Object.values(obj) // [3, 13, 23, 33]
To a large extent, strings can be regarded as String array,
all have length attribute
all have
concat()/ indexOf()
/ includes()
/ slice()
MethodHowever, it is worth noting that there is no method on string that can modify its own content in place, all of which return a new string
string There is also a
repeat() method to create a specified number of string copies.
The above is the detailed content of JS method to convert non-array objects into arrays. For more information, please follow other related articles on the PHP Chinese website!