【问题标题】:interchange array using shift method使用移位方法交换数组
【发布时间】:2015-03-06 08:36:43
【问题描述】:

我正在尝试使用 shift 方法交换数组并打印它,但不确定我是否可以使用它。

Code Snippet 下方。

var points = [40, 100, 1, 5, 25, 10];

//trying to achieve like anotherPoints array
//var anotherPoints = [1, 5, 100, 40, 25, 10];

for (index = 0; index < points.length; index++) {
  points.shift();
  console.log(points);
}

【问题讨论】:

    标签: javascript jquery arrays angularjs backbone.js


    【解决方案1】:

    获得预期结果的一些逻辑:

    var points = [40, 100, 1, 5, 25, 10],
        temp1 = [], temp2 = [], anotherArray;
    points.forEach(function(val){
        if(val < 10 ) {
            temp1.push(val)
        } else {
            temp2.push(val);   
        }
    });
    anotherArray = temp1.sort().concat(temp2.sort(function(a,b){return b- a}));
    alert(anotherArray);

    通过shiftsplice 是不可能的。除非手动创建数组。

    【讨论】:

      【解决方案2】:

      shift() 方法不会移动或交换数组的元素。它类似于pop(),但它从Array中弹出第一个元素。

      例如,

      var points = [40, 100, 1, 5, 25, 10];
      console.log(points.shift());  // 40
      console.log(points); // [100, 1, 5, 25, 10]
      

      对于重新排列数组元素的要求,您将不得不使用 Array.splice() 方法。看看这个问题Reordering arrays

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-06
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 2018-04-13
        相关资源
        最近更新 更多