javascript中索引
There are many tasks related to arrays that sound quite simple but (1) aren't and (2) aren't required of a developer very often. I was encountered with one such task recently: inserting an item into an existing array at a specific index. Sounds easy and common enough but it took some research to figure it out.
与数组相关的许多任务听起来很简单,但开发人员通常不需要(1),也不需要(2)。 最近,我遇到了一个这样的任务:将项目插入到特定索引处的现有数组中。 听起来很容易而且很普通,但是需要进行一些研究才能弄清楚。
// The original array var array = ["one", "two", "four"]; // splice(position, numberOfItemsToRemove, item) array.splice(2, 0, "three"); array; // ["one", "two", "three", "four"]If you aren't adverse to extending natives in JavaScript, you could add this method to the Array prototype:
如果您不反对在JavaScript中扩展本机,则可以将此方法添加到Array原型中:
Array.prototype.insert = function (index, item) { this.splice(index, 0, item); };I've tinkered around quite a bit with arrays, as you may have noticed:
您可能已经注意到,我对数组进行了很多修改:
Remove an Item From an Array
从数组中删除项目
Clone Arrays
克隆数组
Empty Arrays
空数组
Sort Arrays
排序数组
Arrays are super useful -- JavaScript just makes some tasks a bit more ... code-heavy than they need to be. Keep these snippets in your toolbox for the future!
数组非常有用-JavaScript只会使某些任务变得更多……代码繁重。 将这些摘要保存在您的工具箱中,以备将来使用!
翻译自: https://davidwalsh.name/array-insert-index
javascript中索引