【问题标题】:Javascript prototype and modify original objectJavascript原型和修改原始对象
【发布时间】:2020-04-24 01:41:12
【问题描述】:

我们如何更新原型中传递的对象?我已经创建了与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]

我检查了几个例子,但我不知道如何更新原型中的原始对象 我们如何创建一个将更新原始对象的原型(小心:反向是破坏性的——它会改变原始数组。) .

【问题讨论】:

  • 修改this的属性。
  • @Pointy,谢谢。使用相等运算符重新分配此对象时出现错误。我尝试删除和添加所有元素。我会更新答案
  • 我说修改this属性。你不能给this赋值。

标签: javascript arrays prototypal-inheritance prototype-programming array.prototype.map


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您想就地反转数组(如果您愿意,可以返回它),您可以创建一个临时堆栈,方法是弹出数组的头部直到它为空,然后将临时元素推入,就好像它们是排队。

    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(','))

    【讨论】:

      【解决方案3】:

      @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);

      现有数组原型的本地imlimatation的其他链接很少

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多