


Detailed explanation of the steps to convert non-array objects into arrays (with code)
This time I will bring you a detailed explanation of the steps to convert non-array objects to arrays (with code). What are the precautions for converting non-array objects to arrays? 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]
Concise writing method[].slice.call(obj)
Array.from(obj)
This method can convert array-like objects and iterable objects into arrays
Array-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.<a href="http://www.php.cn/code/8145.html" target="_blank"> getElementsByTagName</a>("p")
Returns an iterable object but not an arrayArray.isArray(document.getElementsByTagName('p'))
Returns false
Create iterable objects through generators
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]
Transform the object itself to make it an iterable object
By default, the objects defined by the developer are not Iterate objects, but if you add a generator to the 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]
Method to determine whether an object is an iterable object
typeof obj[Symbol.iterator] === 'function'
A little extension of for of and forEach and for in
for of is used to loop iterable objects, including Array, Set, Map, and strings
And Array, Set, and Map are all There is a forEach method
In addition, NodeList is not an Array, Set, or Map, but an iterable object that can be traversed using for of
In addition, when using for of to loop an object, you can terminate it early through break. And forEach cannot break out of the loop in advance
for in 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 the hasOwnProperty()
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
Anyway, we have gone too far, so let’s go a little further. 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"]
characters String deduplication
[...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中文网其它相关文章!
推荐阅读:
通过jQuery编码转换、事件响应、页面跳转实现浏览器跳转并传递参数
The above is the detailed content of Detailed explanation of the steps to convert non-array objects into arrays (with code). For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
