Raj*_*esh 22 javascript arrays
当我找到Array.of时,我正在做一些阅读.
根据MDN,
无论参数的数量或类型如何,Array.of()方法都会创建一个具有可变数量参数的新Array实例.
var a = Array.of(1,2,3,4,5);
console.log(a)Run Code Online (Sandbox Code Playgroud)
但是如果我已经知道了这些值,我也可以将它们包装起来[]以获得相同的输出.那么我们可以/应该使用的具体情况是Array.of什么?使用它还有什么好处[]吗?
这个问题的目的是Array.ofvs []与new Arrayvs 之间的区别Array.of
Red*_*edu 11
Array.of()和Array()/ []constructor 之间有一个细微的区别.通常情况下就像Array()中,this在Array.of()将成为Array对象,它将使用Array.constructor它function Array()来构建它的结果.
但是,Array.of通过更改它的绑定上下文可以表现不同.如果绑定的上下文可以用作构造函数(如果绑定的对象是函数),它将使用该函数来构造.所以让我们绑定Array.of()一个函数,看看会发生什么.
function Test(n){console.log(n)}
Test.prototype.last = function(){return this[this.length-1]};
var what = Array.of.call(Test, [5,6,7], {a:0,b:1}, 42, null, "this is last");
console.log(JSON.stringify(what,null,2));
console.log(what.last());Run Code Online (Sandbox Code Playgroud)
所以我们得到了一个类似于thingy的数组,可以访问所有函数方法以及构造函数原型中的函数.
最好记住它的定义 ;
注2:功能是一种有意的通用工厂方法; 它不要求它的值是Array构造函数.因此,它可以被传递给或者由可以使用单个数字参数调用的其他构造函数继承.
好的,这对于数组子分类非常方便.我知道数组子类是可能通过涉及Object.setPrototypeOf()或__proto__但它们有点气馁的操作,我们仍然可以在帮助下做类似的工作Array.of().所以......曾经被称为无用的人Array.of()在这里成为英雄; 可能是最有用的数组方法之一.怎么会..?让我们来看看...
function SubArr(){}
SubArr.prototype = Object.create(Array.prototype); // make SubArr.prototype's prototype Array.prototype
SubArr.prototype.last = function(){return this[this.length-1]}; // add prototype methods to SubArr
var what = Array.of.call(SubArr, 1, 2, 3, 4, "this is last");
console.log(JSON.stringify(what,null,2));
console.log(what.last());
console.log(what.map(e => e));
console.log(what instanceof Array);
console.log(Array.isArray(what));
console.log(Object.prototype.toString.call(what));Run Code Online (Sandbox Code Playgroud)
我也试过制作,SubArr.prototype.constructor = Array;但Array.isArray(what)仍然有结果false.