[英]How can I map a prototype function to an array of objects that have that prototype?
[英]How can I return the array object from Array's prototype function?
我有一个编程练习来创建两个Array的原型,它们都是函数。 我把我的代码放在下面。 一个将在另一个上调用,如最后一行所示。 我试图让第二个函数修改通过简单地调用第一个函数返回的值。 这是针对下面的代码,我希望输出为[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
但没有尝试,因为它被弃用,我不能使用它。
请有人帮帮我吗? 我试图阅读原型继承,链接和级联,但似乎无法提取答案。 谢谢你的帮助
在Array.prototype.push
上引用MDN,
push()
方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。
所以, 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 ]
我就是这样做的,
<script>
Array.prototype.toTwenty = function() {
return [4, 6];
};
Array.prototype.search = function(lb) {
if (lb > 2) {
return this.push(4000);
}
};
var man = [];
man = man.toTwenty();
man.search(8);
console.log(man);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.