Javascript原型和修改原始对象



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

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

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

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

如果要就地反转数组(如果需要,可以返回它(,可以通过弹出数组的头部直到它为空,然后像在队列中一样推送临时元素来创建临时堆栈。

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

@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

节点.js更改原型中的数字对象值

最新更新