[英]Is there an analogous way to create an array without its prototype?
Is there something analogous to Object.create(null)
, where the object has no prototype, for an Array
?对于
Array
,是否有类似于Object.create(null)
东西,其中对象没有原型?
var someArray = [];
someArray.__proto__ = null;
No, there is no such thing like Array.create
that creates arrays without a prototype.不,没有像
Array.create
这样的东西可以创建没有原型的数组。 However, __proto__
is despised (it's legacy only), the proper way would be然而,
__proto__
被鄙视(它只是遗产),正确的方法是
var someWeirdArray = Object.setPrototypeOf([], null);
which also has the advantage of being a single expression.它还具有作为单个表达式的优点。
And just a word of caution (that you hopefully don't need): Don't do this!只是一个警告(你希望不需要):不要这样做! There's no good reason.
没有充分的理由。
I know this is old, but for future viewers, if you want to have an array without the weight associated with the prototype, just use Object.create(null)
and key it with numbers.我知道这是旧的,但对于未来的观众,如果你想要一个没有与原型关联的权重的数组,只需使用
Object.create(null)
并用数字键它。
const myEmptyObj = Object.create(null)
myEmptyObj[0] = 'someStuff'
myEmptyObj[1] = 'someOtherStuff'
you might even be able to convince array methods to work on it.你甚至可以说服数组方法来处理它。 I haven't tried this but:
我没有试过这个,但是:
const arrMap = (fn, arr) => Array.prototype.map.call(arr, fn)
where arr
is the object in question and fn
is your map function...其中
arr
是有问题的对象, fn
是您的地图函数...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.