调用此方法时,它会反转原始数组中项目的顺序。然后它返回相同的原始数组。不需要创建新的数组来传递这个kata。
但是,我试图弄清this.push(arr.pop());
在此函数中的工作原理。
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(), []);
或者请写一个你认为更好的解决方案
答案 0 :(得分:4)
我添加了评论:
Array.prototype.reverse = function() {
var arr = this.splice(0); // Removes all entries from `this` array AND returns
// them in a new array
while(arr.length) { // For as long as that new array still has items
// (length is "truthy" until it's 0)
this.push(arr.pop()); // `pop` removes the LAST entry from `arr`, and
// `push` adds it to `this` as the next entry
}
return this;
};
所以说我们有[1, 2, 3, 4, 5]
:
this
移除并放入arr
。arr.length
是5
,我们会进入循环体。arr.pop()
从5
移除arr
。this.push()
将5
添加到this
中的下一个可用位置,该位置位于开头arr.length
现在是4
,所以我们再次进入身体arr.pop()
从4
移除arr
。this.push()
将4
添加到this
中的下一个可用位置,该位置位于5
arr.length
为0
时,它不再真实,我们退出循环答案 1 :(得分:1)
“或者请编写一个您认为更好的解决方案”
这是一个更有效,更简单的解决方案:
WITH user_data AS (
SELECT customer_id, order_total, order_date::DATE,
ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY order_date::DATE DESC
)
AS order_count
FROM transactions
WHERE STATUS = 100 AND order_total > 0
)
SELECT * FROM user_data WHERE order_count < 3;
在支持ECMAScript 6的浏览器中,您可以将其缩短为:
Array.prototype.reverse = function() {
for (var i = 0, j = this.length - 1; i < j; i++, j--) {
var tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
};
不确定是否有额外的开销。