深入js:Array源码篇(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。github仓库:https://github.com/lzcwds,欢迎访问 https://blog.csdn.net/lzcwds/article/details/83313248

一、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开发方面的需要,可以联系我,生活不容易,且行且珍惜。请在博客留言,我会联系你

猜你喜欢

转载自blog.csdn.net/lzcwds/article/details/83313248
今日推荐