function toarray(){
console.log(arguments);
//法1
var x=[].slice.apply(arguments);
console.log(x)
//法1变形
var y=Array.prototype.slice.apply(arguments)
console.log(y)
//法1用call替换apply
var z=Array.prototype.slice.call(arguments)
console.log(z)
//法2,遍历arguments,入数组
var arr=[];
for(var i=0;i<arguments.length;i++){
arr.push(arguments[i]);
}
console.log(arr)
//法3
var m=Array.from(arguments);
console.log(m)
//法4
var xx=[...arguments]//...相当于遍历,[]相当于添加到数组,同法2
console.log(xx)
}
toarray(1,2,3,4)
输出
NodeList转数组
一下代码主要是为Nodelist转换为数组准备的,在IE8及更早的版本,NodeList实现是一个COM对象,使用Array.prototype.slice.apply(nodes)
会导致错误,必须使用遍历
function convertToArray(nodes) {
var arr = null
try {
arr = Array.prototype.slice.apply(nodes)
} catch (ex) {
var len = nodes.length
arr=[]
for (var i = 0; i < len; i++) {
arr.push(nodes[i])
}
}
return arr
}
测试
//html
<div id="fight">加油</div>
//js
function convertToArray(nodes) {
var arr = null
try {
arr = Array.prototype.slice.apply(nodes)
} catch (ex) {
var len = nodes.length
arr=[]
for (var i = 0; i < len; i++) {
arr.push(nodes[i])
}
}
return arr
}
var x = convertToArray(c)
console.log(x)//[text]
console.log(Object.prototype.toString.apply(x))//[object Array]