继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

MYYA
关注TA
已关注
手记 300
粉丝 75
获赞 326

科普 什么是类数组


  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

<!DOCTYPE html><html><head>
    <meta charset="utf-8">
    <title>爱问医康</title></head><body>
    <img id="hitarea" src="http://imgdev.cdn.chspu.com/2018/06/27/a40052fa.jpg" />
    <div ></div>
    <div ></div></body><script src="test.js"></script></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);

webp

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);

webp

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);

webp

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);

webp

image.png

完结

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



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


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP