Summary of JS methods to convert non-array objects to arrays
This article mainly introduces you to some methods of converting JS from non-array objects to arrays, namely Array.prototype.slice.call(obj), Array.from(obj), [...obj] and Object. For detailed implementation methods of values(obj) and other methods, friends in need can refer to it.
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 by generators are iterable objects
document.getElementsByTagName(" 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 all non-iterable objects, but if Symbol.iterator
If you add a generator to the attribute, 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 the 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 all have forEach methods
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 objects, it can be terminated early through break, but forEach cannot jump 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 enumerable properties of the object itself, use hasOwnProperty ()
Method to determine whether the properties are the properties of the object itself
Object.getOwnPropertyNames(obj)
, return the enumerable or non-enumerable properties of the object itself
Anyway, we’ve gone too far, so let’s go a little further, Object.assign()
The method copies the values of all enumerable properties from one or more source objects to the target object
[…obj]
The spread operator can convert an iterable object into an array
For example, [...'obj ']
Return["o", "b", "j"]
String deduplication
[...new Set ('objobj')]
Object.values(obj)
By default, the objects defined by the developer are It is not an iterable object, but provides methods to return iterators
entries()
values()
keys()
By using these methods, you can return the related array
Unlike array-like objects that require objects to have length values, Object .values(obj)
Returns a collection of enumerable attribute values of the object itself
let obj = { '0': 3, '1': 13, '2': 23, '3': 33 } let arr = Object.values(obj) // [3, 13, 23, 33]
The relationship between strings and arrays
To a large extent, you can Treat strings as string arrays,
all have length attributes,
all have concat()
/ indexOf()
/ includes()
/ slice()
Method
However, 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 what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Jquery and PHP combined to achieve AJAX long-term Polling
Jquery specific examples introduce when to use AJAX and where AJAX should be used
The above is the detailed content of Summary of JS methods to convert non-array objects to arrays. For more information, please follow other related articles on the PHP Chinese website!

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.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

Atom editor mac version download
The most popular open source editor

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

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
