如何在原型中更新传递的对象?我已经创建了类似于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来编写一个原型来更新原始对象。
发布于 2020-01-06 14:03:52
不能直接分配this,但仍然可以更改其属性。因此,保持您发布的代码的样式,您可以按照以下方式进行如下操作:
Array.prototype.myReverse = function() {
let arr = [...this]
for (let i = 0; i < this.length; i++) {
this[i] = arr.pop()
}
}发布于 2020-01-06 14:43:01
如果您想将数组反转(如果您愿意的话返回它),您可以通过弹出数组的头部直到数组为空,然后将临时元素推送到队列中来创建一个临时堆栈。
(LILO)
来自temp的(LOFI)
其中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(','))
发布于 2020-01-06 14:09:17
@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://stackoverflow.com/questions/59613346
复制相似问题