栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

javascript 类数组转数组的四种姿势

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

javascript 类数组转数组的四种姿势

科普 什么是类数组

  1. 拥有length属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理,这里你可以当做是个非负整数串来理解)

var aDivs = document.querySelectorAll('div'); // 类数组function hello (){  console.log(arguments);//类数组
  console.log(arguments.length);
}
hello(1);var arr = {'1':'哈哈','2':'呼呼','4':'嘿嘿',length:5};// 类数组var str=Array.prototype.join.call(a,'+');//'+哈哈+呼呼++嘿嘿'//非类数组示例var noArr = {'1':2};   //没有length属性就不是类数组
  • 2.不具有数组所具有的方法

shift,unshift,splice,slice,concat,reverse,sort...
为什么要转换类数组为数组

由于类数组不具有数组所具有的操作数组的方法,将类数组转换为数组之后就能调用如shift,unshift,splice,slice,concat,reverse,sort等这些强大的方法。

如何转换 类数组=>数组

html


    
    爱问医康
    
    
    

第一种 Array.prototype.slice.call(arguments)

var aDivs = document.querySelectorAll('div');console.log("是否是數組 =>",aDivs instanceof Array);var newArr = Array.prototype.slice.call(aDivs);console.log(newArr);console.log("是否是數組 =>",newArr instanceof Array);

image.png

第二种 Array.prototype.concat.apply([],aDivs)

var aDivs = document.querySelectorAll('div');console.log(aDivs);console.log("是否是數組 =>",aDivs instanceof Array);var newArr3 = Array.prototype.concat.apply([],aDivs);
newArr3.push(1);console.log(newArr3);console.log("是否是數組 =>",newArr3 instanceof Array);

image.png

第三种 Array.prototype.splice.apply()

var aDivs = document.querySelectorAll('div');console.log(aDivs);console.log("是否是數組 =>",aDivs instanceof Array);var resultArr = [];var argumentsArr=[0,0];for (var i = 0; i < aDivs.length; i++) {
  argumentsArr.push(aDivs[i]);  
}Array.prototype.splice.apply(resultArr,argumentsArr);console.log(resultArr);console.log("是否是數組 =>",resultArr instanceof Array);

image.png

第四种 新建一个数组,然后直接push进去(这样感觉是在作弊啊 【偷笑脸】)

var aDivs = document.querySelectorAll('div');console.log(aDivs);console.log("是否是數組 =>",aDivs instanceof Array);var resultArr = [];for (var i = 0; i < aDivs.length; i++) {
  resultArr.push(aDivs[i]);  
}console.log(resultArr);console.log("是否是數組 =>",resultArr instanceof Array);

image.png

完结

总结
明显Array.prototype.slice.call(arguments),这种方式优势明显。



作者:小枫学幽默
链接:https://www.jianshu.com/p/2996e48f23e5


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245549.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号