当前位置:网站首页>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
边栏推荐
- Kotlin - improved decorator mode
- PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?
- Luogup3694 Bangbang chorus standing in line
- Anan's doubts
- Smbms project
- Multi table query of MySQL - multi table relationship and related exercises
- Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
- 8皇后问题
- Flink SQL knows why (12): is it difficult to join streams? (top)
- 解决 System has not been booted with systemd as init system (PID 1). Can‘t operate.
猜你喜欢

Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial

Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators

Multi table query of MySQL - multi table relationship and related exercises

IDEA 全文搜索快捷键Ctr+Shift+F失效问题

rxjs Observable filter Operator 的实现原理介绍

已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)

今日睡眠质量记录77分

My creation anniversary: the fifth anniversary
![[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]](/img/8b/bef94d11ac22e3762a570dab3a96fa.jpg)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]

Logseq 评测:优点、缺点、评价、学习教程
随机推荐
Sword finger offer 16 Integer power of numeric value
Resolved (error in viewing data information in machine learning) attributeerror: target_ names
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
Libuv库 - 设计概述(中文版)
显卡缺货终于到头了:4000多块可得3070Ti,比原价便宜2000块拿下3090Ti
Kivy tutorial how to load kV file design interface by string (tutorial includes source code)
This math book, which has been written by senior ml researchers for 7 years, is available in free electronic version
Oracle memory management
Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
[sort] bucket sort
MySQL_ JDBC
阿南的疑惑
luoguP3694邦邦的大合唱站队
刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?
mysql更新时条件为一查询
Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
Anan's doubts
JS 将伪数组转换成数组
道路建设问题