简体   繁体   English

有没有类似的方法来创建没有原型的数组?

[英]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.

相关问题 在 ES5 之前,有没有办法在没有原型的情况下创建对象? - Was there a way to create an object without a prototype prior to ES5? 有没有一种简单的方法可以快速将给定数组的所有内容传递给Array.prototype方法变量而无需使用参数? - Is there a simple way to quickly pass the entire contents of a given array into an `Array.prototype` method variable without using parameters? 使用原型用方法创建一个Array - Using the prototype to create an Array with methods 学习Array.prototype并计算其长度 - Learning Array.prototype and calculating its length 使用原型创建数组,该原型的方法实现对Array原型的包装 - Create array with prototype whose methods implements wrapper over Array prototype Array.prototype没有修改原始数组 - Array.prototype without modifying original array 如何使用默认原型从没有原型的对象创建JS对象? - How to create a JS object with the default prototype from an object without a prototype? 有没有办法在不改变位置的情况下更改对象数组中的项目? - Is there a way to change an item in an array of objects without changing its position? 如何在不使用原型的情况下获得 Object/Array .prototype 的功能? - How to get the functionality of Object/Array .prototype without using prototype? 原型是否在不使用var的情况下创建了变量? - did prototype create a variable without using var?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM