试图理解这个函数:Array.prototype.reverse = function(){

时间:2015-09-11 18:05:00

标签: javascript arrays reverse

调用此方法时,它会反转原始数组中项目的顺序。然后它返回相同的原始数组。不需要创建新的数组来传递这个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(), []);

或者请写一个你认为更好的解决方案

2 个答案:

答案 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]

  1. 首先将这些内容从this移除并放入arr
  2. 然后,由于arr.length5,我们会进入循环体。
  3. arr.pop()5移除arr
  4. this.push()5添加到this中的下一个可用位置,该位置位于开头
  5. arr.length现在是4,所以我们再次进入身体
  6. arr.pop()4移除arr
  7. this.push()4添加到this中的下一个可用位置,该位置位于5
  8. 之后
  9. 冲洗,重复
  10. arr.length0时,它不再真实,我们退出循环

答案 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;
};

不确定是否有额外的开销。