当前位置:网站首页>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
边栏推荐
- R语言gt包和gtExtras包优雅地、漂亮地显示表格数据:nflreadr包以及gtExtras包的gt_plt_winloss函数可视化多个分组的输赢值以及内联图(inline plot)
- sitesCMS v3.1.0发布,上线微信小程序
- 【历史上的今天】7 月 3 日:人体工程学标准法案;消费电子领域先驱诞生;育碧发布 Uplay
- Flink SQL knows why (12): is it difficult to join streams? (top)
- JSP and filter
- 开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
- [Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
- Tencent cloud tdsql database delivery and operation and maintenance Junior Engineer - some questions of Tencent cloud cloudlite certification (TCA) examination
- 2022-01-27 redis cluster cluster proxy predixy analysis
- mysqlbetween实现选取介于两个值之间的数据范围
猜你喜欢
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
剑指 Offer 12. 矩阵中的路径
MyCms 自媒体商城 v3.4.1 发布,使用手册更新
今日睡眠质量记录77分
2022-02-14 analysis of the startup and request processing process of the incluxdb cluster Coordinator
Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
rxjs Observable filter Operator 的实现原理介绍
MySQL installation, uninstallation, initial password setting and general commands of Linux
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
Logseq 评测:优点、缺点、评价、学习教程
随机推荐
OpenHarmony应用开发之ETS开发方式中的Image组件
剑指 Offer 11. 旋转数组的最小数字
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
Seven habits of highly effective people
MySQL installation, uninstallation, initial password setting and general commands of Linux
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
35道MySQL面试必问题图解,这样也太好理解了吧
Introduction to the implementation principle of rxjs observable filter operator
Will Huawei be the next one to fall
luoguP3694邦邦的大合唱站队
R language uses the data function to obtain the sample datasets available in the current R environment: obtain all the sample datasets in the datasets package, obtain the datasets of all packages, and
Logback 日志框架
The difference between stratifiedkfold (classification) and kfold (regression)
DQL basic query
Server coding bug
2022-01-27 research on the minimum number of redis partitions
Image component in ETS development mode of openharmony application development
Task5: multi type emotion analysis
Tencent cloud tdsql database delivery and operation and maintenance Junior Engineer - some questions of Tencent cloud cloudlite certification (TCA) examination
Convolution emotion analysis task4