在编写代码时,有时需要对类数组对象使用forEach、map、filter等迭代操作,而类数组对象无法直接调用这些方法,因而需将其转换为数组。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 100px;
height: 100px;
background-color: blue;
margin-top: 10px;
}
.hi{
background-color:orange;
}
</style>
<script src="./jquery-3.5.0.js"></script>
<script>
window.onload=function(){
var result=$('div');
// 获得一个类数组对象,此处为result
console.log(result);
}
</script>
</head>
<body>
<div class="one" id="oneDiv">hello</div>
<div class="one">world</div>
<div class="one">hello</div>
<div class="one">world</div>
</body>
</html>
所得结果如下
1、用Array.prototype.slice.call(类数组对象)
var result=$('div');
var arr=Array.prototype.slice.call(result);
console.log(arr);
使用Array.prototype.slice.call(类数组对象)之后,成功将类数组对象转换为数组。结果如下
2、用es6中的Array.from(类数组对象)
var result=$('div');
var arr=Array.from(result);
console.log(arr);
使用Array.from(类数组对象)之后,成功将类数组对象转换为数组。结果如下