为了账号安全,请及时绑定邮箱和手机立即绑定

将数组元素从一个数组位置移动到另一个数组位置。

将数组元素从一个数组位置移动到另一个数组位置。

慕妹3146593 2019-07-05 10:09:57
将数组元素从一个数组位置移动到另一个数组位置。我很难弄清楚如何移动数组元素。例如,考虑到以下情况:var arr = [ 'a', 'b', 'c', 'd', 'e'];我如何写一个函数来移动'd'以前'b'?或'a'后'c'?移动后,应更新其余元素的索引。这意味着在移动arr后的第一个例子中,arr[0]将=‘a’,arr[1]=‘d’arr[2]=‘b’,arr[3]=‘c’,arr[4]=‘e’。这看起来应该很简单,但是我不能把我的头绕在这上面。
查看完整描述

3 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

这是我在JSPerf上找到的一条邮轮.。

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);};

读起来很棒,但是如果您想要性能(在小数据集中),请尝试.

 Array.prototype.move2 = function(pos1, pos2) {
    // local variables
    var i, tmp;
    // cast input parameters to integers
    pos1 = parseInt(pos1, 10);
    pos2 = parseInt(pos2, 10);
    // if positions are different and inside array
    if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
      // save element from position 1
      tmp = this[pos1];
      // move element down and shift other elements up
      if (pos1 < pos2) {
        for (i = pos1; i < pos2; i++) {
          this[i] = this[i + 1];
        }
      }
      // move element up and shift other elements down
      else {
        for (i = pos1; i > pos2; i--) {
          this[i] = this[i - 1];
        }
      }
      // put element from position 1 to destination
      this[pos2] = tmp;
    }
  }

我不能接受任何荣誉,这一切都应该归功于理查德·斯卡拉特..它优于本文中针对较小数据集的基于拼接的方法。性能试验..然而,在较大的数据集上,它要慢得多。正如达维恩指出的.


查看完整回答
反对 回复 2019-07-05
  • 3 回答
  • 0 关注
  • 4156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号