gpt4 book ai didi

javascript - 在 javascript 中编辑原型(prototype)方法 .push()

转载 作者:行者123 更新时间:2023-12-01 03:32:27 24 4
gpt4 key购买 nike

我从未使用过原型(prototype),也许我什至不明白它是如何工作的,所以我在这里。

我正在尝试更改 .push() 在 javascript 中的工作方式:它将参数添加为最后一个元素,但我希望它将参数添加到第一个位置.

这是我的无效猜测:

    Array.prototype.push() = function(e){
var x = [e];
return x.concat(this);
}

对我可能犯下的惊人错误表示歉意:)

免责声明:我只是想了解如何修改 native 方法。为什么大家都这么害怕?

最佳答案

只需松开括号:

Array.prototype.push = function(e){
var x = [e];
this.unshift(e);
}

编辑:

如果你不想在里面使用unshift,你可以做splice:

 Array.prototype.push = function(e){
var x = [e];
var y = [];
for(var j = 0; j< this.length; j++) y[j] = this[j];
this[0] = x;
for(var i = 0; i < y.length; i++) this[i+1] = y[i];
}

关于javascript - 在 javascript 中编辑原型(prototype)方法 .push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44470903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com