[英]javascript: is it possible to push objects to an empty array automatically (when they are created)?
[英]Possible to push empty slot to an array?
我正在建立自己的地图方法,使其与本地地图方法一样接近。 由于本机映射将(我认为)更改后的值压入一个新数组,因此它仍然保留空白插槽。 我无法找到将空插槽推入阵列的解决方案,如下面的示例所示。
[1, 2, 3].push(some code) // [1, 2, 3, empty]
我尝试推送一个数组,该数组的一个空项目的前缀为散布运算符arr.push(...(new Array(1)))
或arr.push(...[,])
但这只是推送undefined
。
我通过不使用push来解决问题 ,而是将值分配给数组索引,这样跳过的索引将设置为空。
但是我正在写这篇文章,以查看是否有人知道是否可以使用push方法将空插槽推入数组。
不,这是不可能的,不是push
方法。 仅当数组具有特定长度时才可以存在empty
,但是数组的整数属性在某个索引处不存在。 这称为稀疏数组 ,不能通过push
(或其他数组方法,如果它们是在非稀疏数组上调用的话)创建的。
这样做的唯一方法是将其分配给尚不存在较低索引的索引。
在浏览器控制台而不是代码段控制台中查看以下两个代码段的结果:
const arr = []; arr[1] = 'a'; console.log(arr);
或将数组的.length
设置为该数组具有的最后一个索引上方:
const arr = []; arr.length = 1; console.log(arr);
但是上述两种方法非常奇怪 ,可能没有充分的理由使用。 最好完全避免稀疏数组。
请记住,空插槽不同于undefined
,它很可能具有数组值:
const arr = []; arr.push(undefined); console.log(arr);
您可以通过增加数组长度在数组中创建一个空插槽:
var a = [] a.push(1) a.length++ a.push(3) console.log(a) console.log(1 in a) // anything at index 1?
或者,您可以推送某些内容然后将其删除:
var a = [] a.push(1) a.push(2) a.push(3) delete a[1] console.log(a) console.log(1 in a) // anything at index 1?
实际上,您无需在实现中推送到新数组。 您可以简单地执行new Array(this.length)
,其中this.length
是要通过长度映射的数组。
例如,考虑以下map
实现:
if (!Array.prototype.mapIt) { Object.defineProperty(Array.prototype, "mapIt", { value: function(fn) { if (this === null) { throw new TypeError('Array.prototype.mapIt called on null or undefined'); } if (typeof fn !== 'function') { throw new TypeError('predicate must be a function'); } let _array = this.filter(x => x != null) // remove empty values let result = new Array(_array.length) // the new array we will return for (var i = 0; i < _array.length; i++) { result[i] = fn.call(arguments[1], _array[i], i, _array) // call the predicate } return result; } }); } let arr = [1, 2, , , 3] // the test array let result = arr.mapIt((c, i, a) => console.log(`current: ${c}`, `index: ${i}`, `array: ${a}`) || c + 2) console.log('result: ', result) console.log('original array: ', arr)
希望这对您有所帮助,让您对可能的map
实现有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.