010 手写数组的 push、pop 方法 ?

1/28/2022 JS数组

参照 ecma262 草案的规定,关于 push 和 pop 的规范如下图所示:

project

project

首先来实现一下 push 方法:

Array.prototype.push = function(...items) {
  let O = Object(this);
  let len = this.length >>> 0;
  let argCount = items.length >>> 0;
  // 2 ** 53 - 1 为JS能表示的最大正整数
  if (len + argCount > 2 ** 53 - 1) {
    throw new TypeError("The number of array is over the max value restricted!")
  }
  for(let i = 0; i < argCount; i++) {
    O[len + i] = items[i];
  }
  let newLength = len + argCount;
  O.length = newLength;
  return newLength;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

亲测已通过MDN上所有测试用例。MDN链接 (opens new window)

然后来实现 pop 方法:

Array.prototype.pop = function() {
  let O = Object(this);
  let len = this.length >>> 0;
  if (len === 0) {
    O.length = 0;
    return undefined;
  }
  len --;
  let value = O[len];
  delete O[len];
  O.length = len;
  return value;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

亲测已通过MDN上所有测试用例。MDN链接 (opens new window)

参考链接:

V8数组源码 (opens new window)

ecma262规范草案 (opens new window)

MDN文档 (opens new window)

Last Updated: 1/28/2022, 1:21:13 PM