Javascript(动态)插入数组,然后移动+1下的所有元素 [英] Javascript (dynamic) insert into array, then shift all elements underneath +1

查看:141
本文介绍了Javascript(动态)插入数组,然后移动+1下的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有真正找到针对Javascript的解决方案。
我需要的东西;我想插入一个元素到一个数组中,但并不真正覆盖该元素。而是一个'动态'插入。因此插入元素,然后通过+1索引来移动它下面的所有元素。

Didn't really found a solution to this for Javascript. What I need; I want to insert an element into an array, but not really overwrite that element. Rather a 'dynamic' insert. Thus Insert element, then shift all elements underneath it by +1 index.

例如:

For instance:

I have an array "14S" "16S" "19S".
I know want to insert "15S".
The resulting array: "14S" "15S" "16S" "19S"

我试过:

What i tried:

  fullName = "15S"
  low = 5;
  cardsS[low] = fullName;
  for (var i = low; i < cardsS.length; i++) {
      cardsS[i + 1] = cardsS[i];
  }


推荐答案

您想要插入元素的位置:

使用拼接方法。它很便宜,并且完全符合你的要求。您也可以一次插入多个元素:

Use the splice method. It's cheap and works exactly like you want. You can also insert multiple elements at once:

var strings = ["14S", "16S", "19S"];
strings.splice(1,0,"15S");

结果

Result

"14S" "15S" "16S" "19S"

您也应该使用这个解决方案如果您不希望数组按特定方式排序。

You should also use this solution if you don't want the array to be sorted in a specific way.

如果您不知道要插入元素的位置:

您必须诉诸 push / 排序组合,提供自己的排序算法(除非标准排序足够)

You will have to resort to a push/sort combination, supplying your own sort algorithm (unless the standard sort is enough)

var strings = ["14S", "16S", "19S"];
strings.push("15S");
strings.sort(function(a, b){
    if (a is less than b by some ordering criterion)
        return -1;
    if (a is greater than b by the ordering criterion)
        return 1;
    // a must be equal to b
    return 0;
});

这篇关于Javascript(动态)插入数组,然后移动+1下的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆