1

我在Javascript中有一个数组,如下所示:

var v = new Array("a","b","c","d","e","f"...);

我想反转它但保留前两个元素,所以它会变成:

"a","b",...."f","e","d","c"

我怎样才能做到这一点?

4

5 回答 5

11

试试这个方法:

var v = new Array("a","b","c","d","e","f");
var newArr = v.splice(0,2).concat(v.reverse()); // get the first 2 out of the array
console.log(newArr);
于 2013-09-26T19:06:12.373 回答
5
v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]
于 2013-09-26T19:08:10.573 回答
2
function reverseArrayFromThirdElement(array, copy) {
    var arrayCopy = copy ? array.concat() : array;
    return [array[0], array[1]].concat(
        (arrayCopy.splice(0, 2), arrayCopy.reverse())
    );
}

它允许您选择是否要保护阵列不被切片。copy如果您希望在内部复制数组,则传递为 true。

于 2013-09-26T19:07:31.550 回答
0

它像 C# 中的 Array.Reverse 一样工作:

const arrayReverse = (arr, index, length) => {
    let temp = arr.slice(index, index + length);
    temp.reverse();

    for (let i = 0, j = index; i < temp.length, j < index + length; i++, j++) {
        arr[j] = temp[i];
    }

    return arr;
};

例子:

let test = ['a', 'b', 'c', 'd', 'e', 'f'];
test = arrayReverse(test, 4, 2);

console.log(test); // returns [ 'a', 'b', 'c', 'd', 'f', 'e' ]
于 2017-12-09T23:50:28.937 回答
0

对于就地反转,这可以使用splice方法完成:

let alp = new Array("a","b","c","d","e","f");
alp.splice(2,4,...alp.slice(2).reverse());
console.log(alp);

于 2021-12-12T10:53:34.320 回答