js将伪数组变成真数组的六种方法
js将伪数组变成真数组的六种方法
目的:为了更好的操作DOM 元素,我们将元素转化为数组来操作更为节省时间
html
<div class="box">
<div class="boxchild">box1</div>
<div class="boxchild">box2</div>
<div class="boxchild">box3</div>
</div>
css
*{
padding: 0;
margin: 0;
}
.box{
width: 50%;
display: flex;
justify-content: space-around;
align-items: center;
}
.boxchild{
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
margin: auto 5px;
background: chocolate;
}
js
获取父元素
let obox = document.querySelector(".box");
第一种
let newarr1 = Array.prototype.slice.call(obox.children);
console.log(newarr1);
第二种
let newarr2 = Array.prototype.slice.apply(obox.children)
console.log(newarr2);
第三种
console.log([...(obox.children)])
第四种
let newarr3 = [];
for(var i = 0;i<obox.children.length;i++){
newarr3[i] = obox.children[i]
}
console.log(newarr3)
第五种
let newarr4 = [];
for(var i = 0;i<obox.children.length;i++){
newarr4.push(obox.children[i])
}
console.log(newarr4)
第六种
let newarr5 = Array.from(obox.children);
console.log(newarr5);
完结撒花!!😂😂😂😂
如果当中有写的错误的地方,记得喊我,要是你还有其他方法记得扣我!