当前位置:网站首页>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也能监听数组变化?》
点赞 + 关注 + 收藏 = 学会了
边栏推荐
- Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
- The difference between session and cookie
- Today's sleep quality record 77 points
- Sword finger offer 14- ii Cut rope II
- 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
- 今日睡眠质量记录77分
- sitesCMS v3.0.2发布,升级JFinal等依赖
- 剑指 Offer 12. 矩阵中的路径
- Luogup3694 Bangbang chorus standing in line
- MySQL_ JDBC
猜你喜欢
![[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]](/img/47/78d9dd098dcb894ba1f459873d5f52.png)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]

Flink SQL knows why (12): is it difficult to join streams? (top)

人身变声器的原理
![[data mining review questions]](/img/96/00f866135e06c4cc0d765c6e499b29.png)
[data mining review questions]

Road construction issues

sitesCMS v3.1.0发布,上线微信小程序

18W word Flink SQL God Road manual, born in the sky

Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code

106. 如何提高 SAP UI5 应用路由 url 的可读性

mysql更新时条件为一查询
随机推荐
【習題五】【數據庫原理】
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter 7 exercises]
DQL basic query
对业务的一些思考
Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
Task5: multi type emotion analysis
C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: what is entrustment? P238
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
stm32和电机开发(从mcu到架构设计)
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
开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
Sitescms v3.1.0 release, launch wechat applet
2022-02-09 survey of incluxdb cluster
Finite State Machine FSM
Asp.Net Core1.1版本没了project.json,这样来生成跨平台包
[exercise 5] [Database Principle]
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
Kotlin - 改良装饰者模式
高效能人士的七个习惯
CVPR 2022 image restoration paper