类数组
JS中类数组主要分为这两类类:
1、函数参数对象arguments,包含传入函数中的所有实参集合
箭头函数没有arguments参数
js
function fn() {
console.log(arguments);
}
fn() // [Arguments] {}
fn(1) // [Arguments] { '0': 1 }
fn(1,2,3) // [Arguments] { '0': 1, '1': 2, '2': 3 }
fn([1,2,3]) // [Arguments] { '0': [ 1, 2, 3 ] }1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2、利用querySelectorAll、getElementsByName获取到的NodeList
利用getElementsByTagName、getElementsByClassName获取到的HTMLCollection
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body>
<ul id="ul">
<li name="li" class="li">11</li>
<li name="li" class="li">22</li>
<li name="li" class="li">33</li>
</ul>
</body>
<script>
const a = document.querySelectorAll("li");
const b = document.getElementsByTagName('li');
const c = document.getElementsByClassName('li');
const d = document.getElementsByName('li');
console.log(a, b, c, d);
</script>
</html>
// NodeList(3) [li.li, li.li, li.li]
// HTMLCollection(3) [li.li, li.li, li.li, li: li.li]
// HTMLCollection(3) [li.li, li.li, li.li, li: li.li]
// NodeList(3) [li.li, li.li, li.li]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
类数组与数组的区别
数组遍历可以用 for in和for循环,类数组只能用for循环遍历。
数组对象的类型是Array,类数组对象的类型是object;
类数组不具有数组所具有的方法,类数组不能调用数组的方法
类数组与数组的相同点
相同点:都可用下标访问每个元素,都有length属性。
类数组转数组
既然类数组不能直接使用数组的一些函数,那么在开发的过程中我们有些时候期望拿到类数组之后,将其当作数组使用,可以调用数组的一些函数,那么有哪些方式呢?
使用call、apply改变this指向来调用数组的方法
js
function fn() {
console.log(Array.prototype.slice.call(arguments));
}
fn(1, 2); // [1, 2]1
2
3
4
5
2
3
4
5
数组的slice函数,返回的就是一个真正的数组
Array.from
可以利用数组自带的from函数将类数组转换为数组
js
cosnt arr = Array.from(arguments);1
其返回一个数组
扩展运算符
js
const arr = [...arguments]1
也可以直接在函数接受参数时使用:
js
function fn(...args) {}1
此时在函数内部args就是一个数组了