使用javaScript反转数组的一部分

时间:2013-09-26 19:04:02

标签: javascript arrays

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

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

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

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

我该怎么做?

4 个答案:

答案 0 :(得分:9)

尝试这种方式:

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);

答案 1 :(得分:5)

v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]

答案 2 :(得分: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。

答案 3 :(得分: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' ]