base preguntas cara -js

El código siguiente es la salida:

  let obj = {
    2:3,
    3:4,
    length: 2,
    push: Array.prototype.push
  }

  obj.push(1);
  obj.push(2);
  console.log(obj)

Análisis:
obj es un objeto que tiene cuatro propiedades, incluyendo el método de empuje, en circunstancias normales, el objeto es ningún método push (), entonces lo método push () hacer? O cómo poner en práctica un método push ()?
De la siguiente manera:

	// 实现简易版 push() 方法, 原理:在数组的末尾添加传入的值,改变数组长度并返回数组;
	Array.prototype.push = function(num){
		// this 指向当前Array
		// 默认会使 length 属性加1, 如果没有 length 属性那么 push() 方法会默认 length为0;
		this.length = this.length || 0;
		return this[this.length] = num;
	}
	let arr = [1,2];
	arr.push(3); // => arr = [1,2,3];

() Analizado por el empuje por encima, que puede ser:

	obj.push(1) // => 执行this[this.length] length为2 this[2] = 1;
	obj.push(2) // => 执行this[this.length] length为3 this[3] = 2;
	console.log(obj) // => obj = {2:1, 3:2, length: 4, push: Array.prototype.push} 
Publicado 58 artículos originales · ganado elogios 20 · vistas 110 000 +

Supongo que te gusta

Origin blog.csdn.net/fly_wugui/article/details/105244123
Recomendado
Clasificación