gpt4 book ai didi

javascript - 扩展数组函数出现此错误 "Uncaught TypeError: Object [object Array] has no method ' max'"

转载 作者:行者123 更新时间:2023-11-28 13:36:44 25 4
gpt4 key购买 nike

你好,我正在尝试将此函数构建到我的代码中:

Array.max = function (array) {
return Math.max.apply(Math, array);
};

Array.min = function (array) {
return Math.min.apply(Math, array);
};

根据以下规定: JavaScript: min & max Array values? 。但是,当我尝试使用以下方式调用它时:

console.log(a.max());

哪里

a = [245, 3, 40, 89, 736, 19, 138, 240, 42]

我收到以下错误:

Uncaught TypeError: Object [object Array] has no method 'max' 

有人可以帮我解决这个问题吗?

最佳答案

您必须在原型(prototype)中添加这些函数,而不是在 Array 对象本身上。

Array.prototype.max = function () {
...

Array.prototype.min = function () {
...

除此之外,为了使您的程序正常运行,您必须进行以下更改

Array.prototype.max = function () {
return Math.max.apply(null, this);
};

Array.prototype.min = function() {
return Math.min.apply(null, this);
};

您想在当前 Array 对象上调用这些函数,因此,您必须使用 this 变量,而不是接受数组作为参数。

关于javascript - 扩展数组函数出现此错误 "Uncaught TypeError: Object [object Array] has no method ' max'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876715/

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