Javascript原型和修改原始对象

问题描述 投票:1回答:3

我们如何更新原型中传递的对象?我已经创建了与Array.reverse类似的原型,但是如何修改原始对象?

Array.prototype.myReverse = function() {
  let arr = [];
  for (let i = 0; i < this.length; i++) {
    arr.unshift(this[i]);
  }
  return arr;
}

let a = [9, 0, 3, 4];
console.log("Before ", a); // [9, 0, 3, 4]
console.log("reverse - ", a.myReverse()); // [4, 3, 0, 9]
//not modifying original object , how to modify original object
console.log("After ", a); // [9, 0, 3, 4]

我检查了几个示例,但没有得到如何在原型中更新原始对象的信息我们如何创建将更新原始对象的原型(注意:反向是破坏性的-它会更改原始数组。)如果对于预定义的Array无法实现,那么我们如何创建类似的MyArray来编写用于更新原始对象的原型。

javascript arrays prototypal-inheritance prototype-programming array.prototype.map
3个回答
2
投票

您不能直接分配this,但仍可以更改其属性。因此,保持发布代码的风格,您可以执行以下操作:

Array.prototype.myReverse = function() {
  let arr = [...this]
  for (let i = 0; i < this.length; i++) {
    this[i] = arr.pop()
  }
}

0
投票

如果要就地反转数组(如果需要,可以将其返回),可以通过弹出数组的头直到其为空然后按临时元素的方式推动它们来创建临时堆栈。队列。

  1. 至温度:
    • ARR→POP⇒TMP→PUSH(LILO)
    • ARR→SHIFT⇒TMP→UNSHIFT(FIFO)
  2. 从温度:
    • TMP→POP⇒ARR→UNSHIFT(LOFI)
    • TMP→SHIFT⇒ARR→PUSH(FOLI)

ARR是自引用数组。

if (Array.prototype.reverseItems === undefined) {
  Array.prototype.reverseItems = function() {
    let tmp = []
    while (this.length > 0) tmp.push(this.pop())    // or `tmp.unshift(this.shift()`
    while (tmp.length  > 0) this.unshift(tmp.pop()) // or `this.push(tmp.shift())`
    return this
  }
}

let original = [ 9, 0, 3, 4 ]
original.reverseItems() // in-place
console.log('Reversed:', original.join(','))

-1
投票

@@ pointy感谢您的建议。

我已修改此属性并更新了原始对象

Array.prototype.myReverse = function () {
 let arr = this.slice(); // creating a copy of array
  this.splice(0,this.length); // removing all elements from array
  for(let i = 0; i<arr.length;i++){
    this.unshift(arr[i]);
  }
  return this;
}

let a = [9,0,3,4];

console.log("Before ",a);
console.log("reverse - ", a.myReverse());
console.log("After ", a);

很少有其他链接可以对现有数组原型进行本地化

https://medium.com/@ofirrifo/naive-implementation-of-js-array-methods-a56319cad6b8

https://gist.github.com/alexhawkins/28aaf610a3e76d8b8264

Node.js change Number object value inside prototype

© www.soinside.com 2019 - 2024. All rights reserved.