How to convert non-array objects into arrays
This time I will show you how to convert a non-array object into an array, and what are the precautions for converting a non-array object into an array. The following is a practical case, let's take a look.
Preface
This article mainly summarizes some methods of converting JS from non-array objects to arrays, and shares them for your reference and study. The following is not Enough said, let’s take a look at the detailed introduction.Array.prototype.slice.call(obj)
This method can convert an array-like object into an array, the so-called array-like object, It is an object containing length and index properties. The length of the returned array depends on the value of the length property of the object, and the value of the non-index property, or the 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]
[].slice.call(obj)
Array.from(obj)
This method can convert array-like objects and iterable objects into arraysArray-like objects have been mentioned above. What are iterable objects?- Array, Set, Map and String are all iterable objects (WeakMap/WeakSet are not iterable objects)
- String changes Became an iterable object, solving the coding problem
- These objects have default iterators, that is, they have the Symbol.iterator attribute
- You can use the for of loop
- All iterators created through generators are iterable objects
document.
getElementsByTagName<a href="http://www.php.cn/code/8145.html" target="_blank">("p") </a>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'
Traverse the enumerable properties of the object, including properties on its prototype chain, and the order is not guaranteed
To traverse the object Its own enumerable properties, use thehasOwnProperty() method to determine whether the property is the object's own property
Object.getOwnPropertyNames(obj) , return the object itself to be enumerable Enumerable or non-enumerable attributes
Object.assign() The method changes the values of all enumerable attributes from one or more Source
object copies to target object
[…obj]
The spread operator can convert an iterable object into Array For example, [...'obj'] Returns
["o", "b", "j"]
[...new Set('objobj')]
##Object.values(obj)By default, the objects defined by the developer are all non-iterable objects, but methods are provided to return iterators
- entries()
- values()
- ##keys()
- By using these methods, you can return the related array
与类数组对象需要对象有 length 值不同,Object.values(obj)
返回对象自身可枚举属性值的集合
let obj = { '0': 3, '1': 13, '2': 23, '3': 33 } let arr = Object.values(obj) // [3, 13, 23, 33]
字符串与数组的关系
在很大程度上,可以将字符串看成字符串数组,
都有 length 属性
都有 concat()
/ indexOf()
/ includes()
/ slice()
方法
不过值得注意的是, string 上没有方法可以原地修改它自身的内容,都是返回新的 string
string 还有个 repeat()
方法,创建指定数量的字符串副本
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to convert non-array objects into arrays. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

JSON (JavaScriptObjectNotation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples. Syntax The syntax of the json_encode() function is as follows: st

How to enable the direct connection of the independent graphics card of the Shenzhou Xuanlong m7. To enable the direct connection function of the independent graphics card of the Shenzhou Xuanlong m7, you can follow the following steps: 1. First, make sure that you have installed the driver of the independent graphics card. You can go to the official Shenzhou website or the official website of the independent graphics card manufacturer to download and install the latest driver suitable for your graphics card model. 2. On the computer desktop, right-click a blank space and select "NVIDIA Control Panel" in the pop-up menu (if it is an AMD graphics card, select "AMDRadeon Settings"). 3. In the control panel, find "3D Settings" or a similarly named option and click to enter. 4. In "3D Settings" you need to find "Global Settings" or a similarly named option. Here you can specify the use of a unique

Use Python's __contains__() function to define the containment operation of an object. Python is a concise and powerful programming language that provides many powerful features to handle various types of data. One of them is to implement the containment operation of objects by defining the __contains__() function. This article will introduce how to use the __contains__() function to define the containment operation of an object, and give some sample code. The __contains__() function is Pytho

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

As a world-renowned sports brand, Nike's shoes have attracted much attention. However, there are also a large number of counterfeit products on the market, including fake Nike shoe boxes. Distinguishing genuine shoe boxes from fake ones is crucial to protecting the rights and interests of consumers. This article will provide you with some simple and effective methods to help you distinguish between real and fake shoe boxes. 1: Outer packaging title By observing the outer packaging of Nike shoe boxes, you can find many subtle differences. Genuine Nike shoe boxes usually have high-quality paper materials that are smooth to the touch and have no obvious pungent smell. The fonts and logos on authentic shoe boxes are usually clear and detailed, and there are no blurs or color inconsistencies. 2: LOGO hot stamping title. The LOGO on Nike shoe boxes is usually hot stamping. The hot stamping part on the genuine shoe box will show

What is the resolution of Savior Y7000P when playing CF? The resolution of Savior Y7000P when playing CF is 1920*1080. Because this computer is equipped with a GTX1650 graphics card and an i5-9300H processor, its performance is relatively good and sufficient to meet the needs of games such as CF. At the same time, 1920*1080 is the current resolution of mainstream e-sports monitors, and the image quality and clarity are sufficient. In addition, if there are players with higher requirements, you can appropriately lower the game image quality settings to obtain a smoother gaming experience. In order to enjoy a clearer visual experience, you can adjust the resolution of the Savior y7000p to 2560*1400. This way, you will be able to enjoy higher quality image display. Equipped with the Savior Y7000P 2022 model

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.
