1. 程式人生 > >深入js:Array原始碼篇(一)

深入js:Array原始碼篇(一)

一、push() 和pop()

1.push()

push() 向陣列的末尾新增一個或更多元素,並返回新的長度。

push原始碼如下:

// Appends the arguments to the end of the array and returns the new
// length of the array. See ECMA-262, section 15.4.4.7.
function ArrayPush() {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.push");

  if (%IsObserved(this))
    return ObservedArrayPush.apply(this, arguments);

  var array = TO_OBJECT(this);
  var n = TO_LENGTH_OR_UINT32(array.length);
  var m = %_ArgumentsLength();

  // It appears that there is no enforced, absolute limit on the number of
  // arguments, but it would surely blow the stack to use 2**30 or more.
  // To avoid integer overflow, do the comparison to the max safe integer
  // after subtracting 2**30 from both sides. (2**31 would seem like a
  // natural value, but it is negative in JS, and 2**32 is 1.)
  if (m > (1 << 30) || (n - (1 << 30)) + m > kMaxSafeInteger - (1 << 30)) {
    throw MakeTypeError(kPushPastSafeLength, m, n);
  }

  for (var i = 0; i < m; i++) {
    array[i+n] = %_Arguments(i);
  }

  var new_length = n + m;
  array.length = new_length;
  return new_length;
}

這是v8的原始碼地址 第538行
這裡的程式碼比較簡單,從原始碼中可以看出用法:
方法中可以傳多個引數,引數長度不超過2的30次方

var arr = [1,2];
arr.push(3); //arr--->[1,2,3]  return 3;
arr.push(4,5);//arr--->[1,2,3,4,5]  return 5;

1.pop()

刪除陣列的最後一個元素,並返回新的長度。

// Removes the last element from the array and returns it. See
// ECMA-262, section 15.4.4.6.
function ArrayPop() {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.pop");

  var array = TO_OBJECT(this);
  var n = TO_LENGTH_OR_UINT32(array.length);
  if (n == 0) {
    array.length = n;
    return;
  }

  if (%IsObserved(array))
    return ObservedArrayPop.call(array, n);

  n--;
  var value = array[n];
  %DeleteProperty_Strict(array, n);
  array.length = n;
  return value;
}

這是v8的原始碼地址 第497行
如果arr長度為0,返回undefined

var arr = [1,2];
arr.pop(); //arr--->[1]  return 1
arr.pop(); //arr---->[] return 0;
arr.pop(); //arr---->[] return undefined
push(),pop()功能是通用的; 它不要求它的這個值是一個Array物件。因此,它可以轉移到其他型別的物件以用作方法。函式是否可以成功應用於宿主物件取決於實現。

求個兼職,如果您有web開發方面的需要,可以聯絡我,生活不容易,且行且珍惜。請在部落格留言,我會聯絡你