Javascript原型和修改原始对象

Javascript原型和修改原始对象,javascript,arrays,prototypal-inheritance,prototype-programming,array.prototype.map,Javascript,Arrays,Prototypal Inheritance,Prototype Programming,Array.prototype.map,我们如何更新原型中传递的对象?我已经创建了类似于Array.reverse的原型,但如何修改原始对象呢 Array.prototype.myReverse=function(){ 设arr=[]; for(设i=0;i0)this.unshift(tmp.pop())//或`this.push(tmp.shift())` 还这个 } } 让original=[9,0,3,4] original.reverseItems()//就地 console.log('Reversed:',origina

我们如何更新原型中传递的对象?我已经创建了类似于
Array.reverse
的原型,但如何修改原始对象呢

Array.prototype.myReverse=function(){
设arr=[];
for(设i=0;iconsole.log(“之后”,a);//[9,0,3,4]
您不能直接分配
,但仍可以更改其属性。因此,保持您发布的代码的风格,您可以按照以下方式做一些事情:

Array.prototype.myReverse = function() {
  let arr = [...this]
  for (let i = 0; i < this.length; i++) {
    this[i] = arr.pop()
  }
}
Array.prototype.myReverse=function(){
让arr=[…这个]
for(设i=0;i
@非常感谢您的建议

我已修改此对象的属性并更新了原始对象

Array.prototype.myReverse=函数(){
设arr=this.slice();//创建数组的副本
this.splice(0,this.length);//从数组中删除所有元素

对于(设i=0;i,如果您想在适当的位置反转数组(如果您愿意,还可以返回它),您可以通过弹出数组头直到其为空,然后像在队列中一样推送临时元素来创建临时堆栈

  • 至临时:
    • 啊→流行音乐⇒ TMP→推(LILO)
    • 啊→移位⇒ TMP→取消移位(FIFO)
  • 从临时:
    • TMP→流行音乐⇒ 啊→取消移位(LOFI)
    • TMP→移位⇒ 啊→推动(对开本)
  • 其中,ARR是自参考数组

    if(Array.prototype.reverseItems==未定义){
    Array.prototype.reverseItems=函数(){
    设tmp=[]
    while(this.length>0)tmp.push(this.pop())//或`tmp.unshift(this.shift())`
    而(tmp.length>0)this.unshift(tmp.pop())//或`this.push(tmp.shift())`
    还这个
    }
    }
    让original=[9,0,3,4]
    original.reverseItems()//就地
    
    console.log('Reversed:',original.join(',)
    修改
    此的属性
    @Pointy,Thaks。使用相等运算符重新分配此对象时出错。我尝试删除并添加所有元素。我将在回答中更新我说修改
    的属性。无法为
    赋值。