当前位置:网站首页>JS 将伪数组转换成数组
JS 将伪数组转换成数组
2022-07-03 12:39:00 【德育处主任】
本文简介
点赞 + 关注 + 收藏 = 学会了
<br>
在 JS 中,伪数组 是非常常见的,它也叫 类数组。伪数组可能会给 JS 初学者带来一点困扰。
本文将详细讲解 什么是伪数组,以及分别在 ES5 和 ES6 中将伪数组转换成真正的数组 。
什么是伪数组?
伪数组的主要特征:它是一个对象,并且该对象有 length 属性
比如
let arrayLike = { "0": "a", "1": "b", "2": "c", "length": 3}像上面的 arrayLike 对象,有 length 属性,key 也是有序序列。可以遍历,也可以查询长度。但却不能调用数组的方法。比如 push、pop 等方法。
在 ES6 之前,还有一个常见的伪数组:arguments。
arguments 看上去也很像一个数组,但它没有数组的方法。
比如 arguments.push(1) ,这样做一定会报错。
<br>
除了 arguments 之外,NodeList 对象表示节点的集合也是伪数组,比如通过 document.querySelectorAll 获取的节点集合等。
<br>
<br>
转换
将伪数组转换成真正的数组的方法不止一个,我们先从 ES5 讲起。
<br>
ES5 的做法
在 ES6 问世之前,开发者通常需要用以下的方法把伪数组转换成数组。
<br>
方法1
// 通过 makeArray 方法,把数组转成伪数组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);// 输出: [1, 2, 3]这个方法虽然有效,但要多写很多代码。
<br>
方法2
function doSomething () { let args = Array.prototype.slice.call(arguments); console.log(args);}doSomething(1, 2, 3);// 输出: [1, 2, 3]这个方法的功能和 方法1 是一样的,虽然代码量减少了,但不能很直观的让其他开发者觉得这是在转换。
<br>
ES6的做法
直到 ES6 提供了 Array.from 方法完美解决以上问题。
function doSomething () { let args = Array.from(arguments); console.log(args);}doSomething('一', '二', '三');// 输出: ['一', '二', '三']Array.from 的主要作用就是把伪数组和可遍历对象转换成数组的。
<br>
说“主要作用”的原因是因为 Array.from 还提供了2个参数可传。这样可以延伸很多种小玩法。
Array.from 的第二个参数是一个函数,类似 map遍历 方法。用来遍历的。
Array.from 的第三个参数接受一个 this 对象,用来改变 this 指向。
<br>
第三个参数的用法(不常用)
let helper = { diff: 1, add (value) { return value + this.diff; // 注意这里有个 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 其他玩法
创建长度为5的数组,且初始化数组每个元素都是1
let array = Array.from({length: 5}, () => 1)console.log(array)// 输出: [1, 1, 1, 1, 1]第二个参数的作用和 map遍历 差不多的,所以 map遍历 有什么玩法,这里也可以做相同的功能。就不多赘述了。
<br>
把字符串转换成数组
let msg = 'hello';let msgArr = Array.from(msg);console.log(msgArr);// 输出: ["h", "e", "l", "l", "o"]如果传一个真正的数组给 Array.from 会返回一个一模一样的数组。
<br>
<br>
推荐阅读
《Object.defineProperty也能监听数组变化?》
点赞 + 关注 + 收藏 = 学会了
边栏推荐
- 106. How to improve the readability of SAP ui5 application routing URL
- Elk note 24 -- replace logstash consumption log with gohangout
- Logseq 评测:优点、缺点、评价、学习教程
- C graphical tutorial (Fourth Edition)_ Chapter 15 interface: interfacesamplep271
- SSH登录服务器发送提醒
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第六章习题】
- Reptile
- IDEA 全文搜索快捷键Ctr+Shift+F失效问题
- 用户和组命令练习
- When we are doing flow batch integration, what are we doing?
猜你喜欢

今日睡眠质量记录77分

My creation anniversary: the fifth anniversary

February 14, 2022, incluxdb survey - mind map

这本数学书AI圈都在转,资深ML研究员历时7年之作,免费电子版可看

Dojo tutorials:getting started with deferrals source code and example execution summary

PowerPoint tutorial, how to save a presentation as a video in PowerPoint?
![[colab] [7 methods of using external data]](/img/cf/07236c2887c781580e6f402f68608a.png)
[colab] [7 methods of using external data]

Logseq 评测:优点、缺点、评价、学习教程

Idea full text search shortcut ctr+shift+f failure problem

Road construction issues
随机推荐
2022-02-11 practice of using freetsdb to build an influxdb cluster
Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication
CVPR 2022 图像恢复论文
When the R language output rmarkdown is in other formats (such as PDF), an error is reported, latex failed to compile stocks Tex. solution
Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
json序列化时案例总结
父亲和篮球
The difference between stratifiedkfold (classification) and kfold (regression)
STM32 and motor development (from MCU to architecture design)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter V exercises]
Asp.Net Core1.1版本没了project.json,这样来生成跨平台包
已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)
Task5: multi type emotion analysis
Today's sleep quality record 77 points
Logback log framework
Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
Sword finger offer 12 Path in matrix
2022-02-13 plan for next week
SLF4J 日志门面
剑指 Offer 14- I. 剪绳子