當這個方法被調用時,它反轉原始數組中的項目的順序。然後它返回相同的原始數組。不需要創建新陣列來傳遞這個kata。 但是,我試圖弄清楚this.push(arr.pop());
在這個函數中的工作原理。試圖瞭解此函數:Array.prototype.reverse =函數(){
Array.prototype.reverse = function() {
var arr = this.splice(0); //I understand first we remove all the items in the array starting from [0]
while(arr.length) { //then we run the arr.length of all the items?
this.push(arr.pop()); //then add the deleted last item? doesn't make sense...
}
return this;
};
測試用例:
Test.assertSimilar([1, 2, 3, 4].reverse(), [4,3,2,1]);
Test.assertSimilar(["a", "b", "c"].reverse(), ["c", "b", "a"]);
Test.assertSimilar([].reverse(), []);
或請寫出你認爲一個功能是一個更好的解決方案