当前位置:网站首页>JS convert pseudo array to array
JS convert pseudo array to array
2022-07-03 13:21: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 .
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
边栏推荐
- Some thoughts on business
- SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
- Seven habits of highly effective people
- MySQL installation, uninstallation, initial password setting and general commands of Linux
- Logseq 评测:优点、缺点、评价、学习教程
- The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti
- 开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
- [Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
- Smbms project
- SSH login server sends a reminder
猜你喜欢

AI 考高数得分 81,网友:AI 模型也免不了“内卷”!

人身变声器的原理

The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti

用户和组命令练习

Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication

MySQL constraints

My creation anniversary: the fifth anniversary

Kivy教程之 如何自动载入kv文件

35道MySQL面试必问题图解,这样也太好理解了吧

MyCms 自媒体商城 v3.4.1 发布,使用手册更新
随机推荐
File uploading and email sending
JSP and filter
Anan's doubts
Resolved (error in viewing data information in machine learning) attributeerror: target_ names
SQL learning notes (I)
MySQL installation, uninstallation, initial password setting and general commands of Linux
71 articles on Flink practice and principle analysis (necessary for interview)
Introduction to the implementation principle of rxjs observable filter operator
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]
Sword finger offer 12 Path in matrix
PowerPoint tutorial, how to save a presentation as a video in PowerPoint?
When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
Luogup3694 Bangbang chorus standing in line
Setting up remote links to MySQL on Linux
Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
今日睡眠质量记录77分
Task6: using transformer for emotion analysis
Elk note 24 -- replace logstash consumption log with gohangout
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆