Javascript Array Push 代码如何在内部工作

How does the Javascript Array Push code work internally

本文关键字:在内部 工作 代码 Array Push Javascript      更新时间:2023-09-26

javascript中Push and Pop方法的内部代码逻辑是什么..??推送方法如何将值存储在数组中。

pushpop 方法是有意泛型的,它们仅依赖于 length 属性的存在,并且可以添加和删除属性。

push 方法将读取 length 属性,添加具有该名称的属性,并增加长度。基本上:

function push(value) {
  var len = this.length;
  this[len] = value;
  len++;
  this.length = len;
  return len;
}

pop 方法将读取 length 属性,减少它,获取具有该名称的属性并删除该属性。基本上:

function pop() {
  var len = this.length - 1;
  var value = this[len];
  this.length = len;
  delete this[len];
  return value;
}

实际的实现稍微复杂一些,因为它们支持例如push方法的多个参数,以及更多的错误检查。当对象实际上是一个数组时,也可能实现特殊的优化代码,但对于其他对象,通用代码仍然存在。

这些方法是有意泛型的,以便它们可以用于实际上不是数组的对象。您可以通过仅具有length属性来创建自己的支持它们的对象:

var o = {
  length: 0,
  push: Array.prototype.push,
  pop: Array.prototype.pop
};
o.push(1);
var one = o.pop();

演示:http://jsfiddle.net/Guffa/9r4gavzb/

我们可以尝试一些测试和测试行为:

const arr1 = []
const { push: push1 } = arr
const arr2 = []
const { push: push2 } = arr
console.log(push1 === push2) // true
console.log(push1 === Array.prototype.push) // true
push1(1) // TypeError: Cannot convert undefined or null to object
push1.call(arr1, 1) // arr1: [1], arr2: []
push2.call(arr1, 2) // arr1: [1, 2], arr2: []
push1.bind(arr2)(1) // arr1: [1, 2], arr2: [1]
push.call(arr2, 2)

我们可以说push方法在引擎盖下使用this......