我们如何更新原型中传递的对象?我已经创建了与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()
}
}
如果要就地反转数组(如果需要,可以将其返回),可以通过弹出数组的头直到其为空然后按临时元素的方式推动它们来创建临时堆栈。队列。
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