[英]Javascript: How to insert a hole into a sparse array or creating a hole
I'm using sparse arrays to be memory efficient with huge datasets.我正在使用稀疏的 arrays 来高效处理庞大的数据集 memory。 (and to signal the difference between a hole and a undefined
or null
entry) adding holes at the end is fine by setting datapoints.lentgh
. (并表示孔和undefined
或null
条目之间的区别)通过设置datapoints.lentgh
在末尾添加孔是可以的。
datapoints = [10,,,20,,,10,1]
No I face the problem how to insert a hole (say before 20)不,我面临如何插入孔的问题(比如 20 之前)
datapoint.splice(3,0)
does not work, and I can't find a (easy) method to insert holes.不起作用,我找不到插入孔的(简单)方法。 (Think I have to rebuild the array but thought to ask before) Or is there a way to change a "defined" entry into a hole? (认为我必须重建数组但想过问过)或者有没有办法将“定义的”条目更改为一个洞? delete datapoint[4];
creates an undefined entry not a hole:(创建一个未定义的条目而不是一个洞:(
Your sparse array is actually an object. You can delete items and you can add items.您的稀疏数组实际上是一个 object。您可以删除项目,也可以添加项目。
Let's suppose you want to add k
holes before position offset
.假设您想在 position offset
之前添加k
个孔。 Then:然后:
datapoints = [10,,,20,,,10,1]; function addHoles(offset, k, datapoints) { let migration = {}; for (let key in datapoints) { let intKey = parseInt(key); if (intKey >= offset) { migration[intKey] = datapoints[intKey]; delete datapoints[intKey]; } } for (let key in migration) { let intKey = parseInt(key); datapoints[intKey + k] = migration[intKey]; } return datapoints; } console.log(addHoles(3, 3, datapoints));
Think I could work with认为我可以一起工作
datapoint.splice(3,0,undefined);
delete datapoint[3]
It looks like that I have a hole now....看来我现在有一个洞......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.