我们如何更新原型中传递的对象?我创建了与相似的原型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来编写用于更新原始对象的原型。
您不能this
直接分配,但仍可以更改其属性。因此,保持发布代码的风格,您可以执行以下操作:
Array.prototype.myReverse = function() {
let arr = [...this]
for (let i = 0; i < this.length; i++) {
this[i] = arr.pop()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句