我正在寻找一个JavaScript数组插入方法,样式如下:

arr.insert(index, item)

最好是在jQuery中,但此时任何JavaScript实现都可以。


当前回答

var array= [10,20,30,40]

var i;

var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/

var value=5 
//value to insert

//Initialize from last array element

for(i=array.length-1;i>=pos-1;i--){

array[i+1]=array[i]

}

array[pos-1]=value

console.log(array)

其他回答

按以下方式计算减少方法的利润:

function insert(arr, val, index) {
    return index >= arr.length
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

因此,通过这种方式,我们可以返回一个新数组(这将是一种很酷的函数方式,比使用push或splice要好得多),其中元素插入索引处,如果索引大于数组长度,则将在末尾插入。

除了拼接,您可以使用这种方法,它不会改变原始数组,但会使用添加的项创建一个新数组。当你需要避免突变时,它是有用的。我在这里使用ES6排列运算符。

常量项=[1,2,3,4,5]常量插入=(arr,索引,newItem)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10)console.log(结果)// [1, 10, 2, 3, 4, 5]

这可以用于添加多个项目,方法是稍微调整函数,为新项目使用rest运算符,并在返回的结果中传播:

常量项=[1,2,3,4,5]常量插入=(arr,索引,…newItems)=>[//数组的指定索引之前的部分…arr.slice(0,索引),//插入的项目…新项目,//指定索引之后的数组的一部分…arr.slice(索引)]常量结果=插入(项,1,10,20)console.log(结果)// [1, 10, 20, 2, 3, 4, 5]

在这种情况下,我建议使用纯JavaScript。JavaScript中也没有任何insert方法,但我们有一个内置Array方法,它为您完成任务。这叫做拼接。。。

让我们看看什么是拼接()。。。

splice()方法通过删除现有元素和/或添加新元素。

好的,假设我们有下面这个数组:

const arr = [1, 2, 3, 4, 5];

我们可以这样删除3个:

arr.splice(arr.indexOf(3), 1);

它将返回3,但如果我们现在检查arr,我们有:

[1, 2, 4, 5]

到目前为止,还不错,但我们如何使用拼接将新元素添加到数组中?

让我们把三个放回。。。

arr.splice(2, 0, 3);

让我们看看我们做了什么。。。

我们再次使用拼接,但这次对于第二个参数,我们传递了0,这意味着我们不想删除任何项,但同时,我们添加了第三个参数,即将在第二个索引中添加的3。。。

您应该知道,我们可以同时删除和添加。例如,现在我们可以做到:

arr.splice(2, 2, 3);

这将删除索引2中的两个项目。然后在索引2处添加3,结果将是:

[1, 2, 3, 5];

这显示了拼接中的每个项目是如何工作的:

array.拼接(开始,删除计数,项目1,项目2,项目3…)

这是我在一个应用程序中使用的一个工作函数。

这将检查项目是否存在:

let ifExist = (item, strings = [ '' ], position = 0) => {
     // Output into an array with an empty string. Important just in case their isn't any item.
    let output = [ '' ];
    // Check to see if the item that will be positioned exist.
    if (item) {
        // Output should be equal to an array of strings.
        output = strings;
       // Use splice() in order to break the array.
       // Use positional parameters to state where to put the item
       // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
        output.splice(position, 0, item);
    }
    // Empty string is so we do not concatenate with comma or anything else.
    return output.join("");
};

然后我把它叫做下面。

ifExist("friends", [ ' ( ', ' )' ], 1)}  // Output: ( friends )
ifExist("friends", [ ' - '], 1)}  // Output:  - friends
ifExist("friends", [ ':'], 0)}  // Output:   friends:

使用Array.prototype.splice()是实现它的一种简单方法

常量数=[“一”、“二”、“四”、“五”]数字拼接(2,0,“三”);console.log(数字)

阅读有关Array.prototype.splice的更多信息