gpt4 book ai didi

javascript - 如何从 Array 的原型(prototype)函数返回数组对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:44:49 28 4
gpt4 key购买 nike

我有一个编程练习来创建数组的两个原型(prototype),它们都是函数。我把我的代码放在下面。一个将调用另一个,如最后一行所示。我试图让第二个函数修改只需调用第一个函数就可以返回的值。对于下面的代码,我希望输出为 [4,6,4000],我改为在推送后获取数组的长度,即在本例中为 3。

Array.prototype.toTwenty = function() 
{
return [4,6];
};
Array.prototype.search = function (lb)
{

if(lb >2)
{
//This doesn't work
return this.push(4000);
}
};

var man = [];
console.log(man.toTwenty().search(6));

//console.log returns 3, I need it to return [4,6,4000]

我的搜索将我带到 arguments.callee.caller 但我没有尝试,因为它已被弃用,我无法使用它。

有人能帮帮我吗?我试图阅读原型(prototype)继承、链接和级联,但似乎无法提取答案。感谢您的帮助

最佳答案

Array.prototype.push 上引用 MDN ,

The push() method adds one or more elements to the end of an array and returns the new length of the array.

因此,this.push(4000) 实际上压入了值,但是当您返回 push 的结果时,您得到的是数组的当前长度是 3


相反,您应该像这样返回数组对象本身

Array.prototype.toTwenty = function () {
return [4, 6];
};

Array.prototype.search = function (lb) {
if (lb > 2) {
this.push(4000); // Don't return here
}
return this; // Return the array object itself.
};

console.log([].toTwenty().search(6));
// [ 4, 6, 4000 ]

关于javascript - 如何从 Array 的原型(prototype)函数返回数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827579/

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