那么这两个函数之间有什么区别呢?
它们都创建了new Array对象。到目前为止,我发现的唯一不同是Array.from支持ArrayLike参数。我看不出他们为什么没有添加对ArrayLike函数的Array.prototype.map支持。
我是不是遗漏了什么?
发布于 2014-09-26 06:04:22
Array.from()的目的是接收非数组(但类似数组)对象,并将其复制到实际数组中。这允许您使用副本上的所有数组方法,包括仅迭代它的内容,如.splice()、.sort()、.push()、.pop()等.这显然比仅仅让.map()处理类似数组的东西更有能力。
发布于 2016-05-18 18:25:43
Array.map似乎也更有表现力:
var a = () => [{"count": 3},{"count": 4},{"count": 5}].map(item => item.count);
var b = () => Array.from([{"count": 3},{"count": 4},{"count": 5}], x => x.count);
var iterations = 1000000;
console.time('Function #1');
for(var i = 0; i < iterations; i++ ){
b();
};
console.timeEnd('Function #1')
console.time('Function #2');
for(var i = 0; i < iterations; i++ ){
a();
};
console.timeEnd('Function #2')在此页面上使用Chrome (65.0.3325.181版)运行这段代码,结果如下:
Function #1: 520.591064453125ms
Function #2: 33.622802734375ms发布于 2020-01-03 16:18:53
静态方法与实例方法
我知道自从提出这个问题以来,已经过去了很多时间。人们说了很多好话。但我想再补充一些。如果我们试图确定这两种方法的性质,我们可以说Array.from与任何数组实例没有关系。它是一种静态方法,如Array.isArray或Array.of。您还具有数组对象的静态属性(如length )。作为一种静态方法,Array.from 不能从实例调用。例如:
var indexes=[0,1,2,3]
index.from()
>>> index.from is not a function另一方面,如果您编写Array.map(),您将得到一个Array.map is not a function。这是因为Array.prototype.map存在于数组实例中。在我们的小示例中,索引是Array的一个实例,然后在其上使用map。示例
var indexes=[0,1,2,3]
function doubleIt(x){
return 2*x;
}
indexes.map(doubleIt);对于array.from,它应该类似于
Array.from(indexes, doubleIt)我在vscode上使用vscode来评估windows机器上vs代码的性能。这不是性能基准测试的真实情况。但有个主意是有帮助的。我得出的结论与@rileynet映射似乎更有表现力,但只适用于大型数组。
var N=10
var tabIndex=[ ...Array(N).keys()]
function doubleIt(x){
return 2*x;
}
tabIndex.map(doubleIt);/*?.*/ 0.040ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.009ms如果是N=100
tabIndex.map(doubleIt);/*?.*/ 0.052ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.041ms如果是N=1000
tabIndex.map(doubleIt);/*?.*/ 0.228ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.339ms如果是N=10000
tabIndex.map(doubleIt);/*?.*/ 2.662ms
Array.from(tabIndex, doubleIt)/*?.*/ 1.847msN=100000
tabIndex.map(doubleIt);/*?.*/ 3.538ms
Array.from(tabIndex, doubleIt)/*?.*/ 11.742mshttps://stackoverflow.com/questions/26052699
复制相似问题