当前位置:网站首页>JS convert pseudo array to array
JS convert pseudo array to array
2022-07-23 18:23:00 【Director of Moral Education Department】
Brief introduction
give the thumbs-up + Focus on + Collection = Learned to
<br>
stay JS in , Pseudo array It's very common , It's also called An array of class . Pseudo arrays may give JS A little trouble for beginners .
This article will explain in detail What is a pseudo array , And in ES5 and ES6 Convert pseudo arrays into real arrays .
<br> <br>
What is a pseudo array ?
The main features of pseudo arrays : It's an object , And the object has length attribute
such as
let arrayLike = { "0": "a", "1": "b", "2": "c", "length": 3} Like above arrayLike object , Yes length attribute ,key It is also an ordered sequence . Traversable , You can also query the length . But you can't call array methods . such as push、pop Other methods .
stay ES6 Before , There is also a common pseudo array :arguments.
arguments It also looks like an array , But it has no method of array .
such as arguments.push(1) , Doing so will definitely report an error .
<br>
except arguments outside ,NodeList The collection of objects representing nodes is also a pseudo array , Such as through document.querySelectorAll Get the node set, etc .
<br>
<br>
transformation
There is more than one way to convert a pseudo array into a real array , Let's start with ES5 Speak up .
<br>
ES5 How to do it
stay ES6 Before it came out , Developers usually need to use the following methods to convert pseudo arrays into arrays .
<br>
Method 1
// adopt makeArray Method , Turn an array into a pseudo array function makeArray(arrayLike) { let result = []; for (let i = 0, len = arrayLike.length; i < len; i++) { result.push(arrayLike[i]); } return result;}function doSomething () { let args = makeArray(arguments); console.log(args);}doSomething(1, 2, 3);// Output : [1, 2, 3]This method works , But write a lot more code .
<br>
Method 2
function doSomething () { let args = Array.prototype.slice.call(arguments); console.log(args);}doSomething(1, 2, 3);// Output : [1, 2, 3]The function of this method and Method 1 It's the same , Although the amount of code has been reduced , But it can't intuitively make other developers feel that this is a transformation .
<br>
ES6 How to do it
until ES6 Provides Array.from The method perfectly solves the above problems .
function doSomething () { let args = Array.from(arguments); console.log(args);}doSomething(' One ', ' Two ', ' 3、 ... and ');// Output : [' One ', ' Two ', ' 3、 ... and ']Array.from Its main function is to convert pseudo arrays and traversable objects into arrays .
<br>
say “ The main role ” The reason is that Array.from It also provides 2 Parameters can be transferred . This can extend many kinds of small play .
Array.from The second argument to is a function , similar map Traverse Method . Used to traverse .
Array.from The third parameter of accepts a this object , To change this Point to .
<br>
Usage of the third parameter ( Not commonly used )
let helper = { diff: 1, add (value) { return value + this.diff; // Notice there's one here this }};function translate () { return Array.from(arguments, helper.add, helper);}let numbers = translate(1, 2, 3);console.log(numbers); // 2, 3, 4<br>
Array.from Other ways of playing
Create a length of 5 Array of , And every element of the initialization array is 1
let array = Array.from({length: 5}, () => 1)console.log(array)// Output : [1, 1, 1, 1, 1]The function of the second parameter and map Traverse About the same , therefore map Traverse What's the way to play , The same function can be done here . I won't go into details .
<br>
Convert a string to an array
let msg = 'hello';let msgArr = Array.from(msg);console.log(msgArr);// Output : ["h", "e", "l", "l", "o"] If you pass a real array to Array.from Will return an identical array .
<br>
<br>
Recommended reading
《JS This time, you can really prohibit constant modification !》
《JS ES5 You can also create constants ?》
《Object.defineProperty Can also monitor array changes ?》
《Fabric.js From entry to expansion 》
give the thumbs-up + Focus on + Collection = Learned to
边栏推荐
- Activity Registration: how to quickly start the open source tapdata live data platform on a zero basis?
- rhcsa笔记三
- SQLZOO——BBC QUIZ
- 平安过暑假,安全不放假!这些暑期安全小提示请收好
- serialization and deserialization
- 搭建PHP开发环境(Apache+PHP+MySQL)「建议收藏」
- Analyze the CPU surge of an RFID tag system written by.Net
- Machine learning (9) - Feature Engineering (3) (supplementary)
- Stack / heap / queue question brushing (medium)
- Multithreaded programming
猜你喜欢

(11) STM32 - IO pin multiplexing and mapping

Data concentration analysis and data distribution

如何理解:普通代码块、构造块、静态块?有什么关系?

变分法 (Calculus of Variations)

Deep learning learning record - update of learning rate of optimizer

平安过暑假,安全不放假!这些暑期安全小提示请收好

go中高并发下的锁是如何工作的(结合源码)

Information theory: introduction and information measures

rhcsa笔记七

MySQL事务,从redo log、bin log、undo log说起...
随机推荐
Data crawling and display of e-commerce platform based on scratch
Awk from introduction to earth (16) comprehensive case of awk
MySQL classic exercises and answers, 50 common SQL sentence exercises
SQLZOO——BBC QUIZ
rhcsa笔记七
rhcsa笔记三
Non inherited polymorphic ideas cooperate with typeID to realize the transmission of different parameters
Detailed explanation of common curl commands and parameters
Major optimization of openim - Message loading on demand, consistent cache, uniapp Publishing
MySQL事务,从redo log、bin log、undo log说起...
Mutual certification of product compatibility between tapdata and Youxuan database
Analyze the CPU surge of an RFID tag system written by.Net
Use moment to get the date of the current day and the next day
Seal player IP and machine code and unlock the blocked tutorial
CSDN custom T-shirts are waiting for you to get, and the benefits of new programmer are coming!
Boss online replay: the mistake I made when training Dall · e
There is an error prompt when configuring the GOM engine login: the necessary patch file is not found!
Rhcsa Notes 6
数据库建模
Tencent tore open the "fig leaf" of China's NFT