首页 > 代码中把object对象转换为array对象的两种方式的不同?

代码中把object对象转换为array对象的两种方式的不同?

在做练习的时候发现通过“Array.prototype.slice.call()”和“Array.apply()”都可以得到最后的数组(详细请看代码),有些纠结,所以有两个疑问希望得到更多人关于它们的解读
1、这两种方式最后获得数组"real"和"realother"在使用中有陷阱吗?
2、这两种方式哪种方式比较常用?它的优势?

var arrayish = document.body.getElementsByTagName("p");
var real = Array.prototype.slice.call(arrayish, 0);
var realother=Array.apply(null,arrayish);

运行下这个2个片段的代码,你就知道区别啦

var arrayish=[1,2,3,4,5];
var real = Array.prototype.slice.call(arrayish, 0);
var realother=Array.apply(null, arrays);

console.log(real.length);//5
console.log(real[0]);//1
console.log(realother.length);//5
console.log(realother[0]);//1

但是

var arrayish=[1];
var real = Array.prototype.slice.call(arrayish, 0);
var realother=Array.apply(null, arrays);

console.log(real.length);//1
console.log(real[0]);//1
console.log(realother.length);//1
console.log(realother[0]);//undefined

Array.apply调用了Array的构造函数,构建一个Array对象,用不用new都是一个效果
Array的构造函数传入的参数类型有
A. new Array(element0, element1[, ...[, elementN]]);
B. new Array(arrayLength);
A形式的将element0~ elementN按其设置的顺序作为Array实例对象的元素
B形式将会构建一个长度为arrayLength的数组对象,但数组对象为空

在arrayish长度为1,并且元素值为数字时,就会调用B形式的构造函数

【热门文章】
【热门文章】