使用移位方法交换数组

interchange array using shift method

我正在尝试交换数组并使用 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);
}

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.

获得所需结果的一些逻辑:

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。除非手动创建数组。