前言
当我们得到一个伪数组数据的时候,我们应该如何操作才能将其转变为真实数组,并使它能够使用数组的方法呢?本文列举了两个方法,一起来看下吧~
一、伪数组
1. 概念
- 具有 length 属性
- 按索引方式存储数据
- 不具有数组的 push.pop 等方法
伪数组(类数组):
- 无法直接调用数组方法或期望 length 属性有什么特殊的行为,不具有数组的 push.pop 等方法,但仍可以对真正数据遍历方法来遍历它们。
- 典型的是函数document.childnodes 之类的,它们返回的 nodeList 对象都属于伪数组。
2. 目标
将伪数组转换为真实的数组,使其可以使用数组的方法。
二、实现方式
1. 方式一
使用js内置对象Array.from()
Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
语法:
Array.from(arrayLike[, mapFn[, thisArg]])
参数说明:
- arrayLike
想要转换成数组的伪数组对象或可迭代对象。- mapFn 可选
如果指定了该参数,新数组中的每个元素会执行该回调函数。- thisArg 可选
可选参数,执行回调函数 mapFn 时 this 对象。
代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
let eleArr = document.querySelectorAll('li')
console.log('伪数组', eleArr)
let transArr = Array.from(eleArr)
console.log('transArr', transArr)
</script>
</body>
</html>
2. 方式二
类数组(Array-like)对象
slice 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的 arguments 就是一个类数组对象的例子。
除了使用 Array.prototype.slice.call(arguments),你也可以简单的使用 [].slice.call(arguments) 来代替。
代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
let eleArr = document.querySelectorAll('li')
console.log('伪数组', eleArr)
function list(arr) {
return Array.prototype.slice.call(arr)
}
let transArr = list(eleArr)
console.log('transArr', transArr)
</script>
</body>
</html>
以下是上述两种方式的运行结果,均已实现我们要将伪数组转换为真实数组的需求。
总结
No man is the whole of himself; his friends are the rest of him.A young idler, an old beggar.