我已经声明了数组原型(prototype) myArrayMax,并且在 w3schools.com 上的其他资源反复验证后,代码似乎是正确的:
该代码用于查找给定数组中的最大数字。
但是,它不起作用,控制台显示以下错误消息:
Uncaught TypeError: points.myArrayMax is not a function
我在这个原型(prototype)声明中找不到问题
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points.myArrayMax();
var len, max;
Array.prototype.myArrayMax = function() {
len = this.length;
max = -Infinity;
while (len--) {
if (this[len] > max) {
max = this[len];
}
}
return max;
}
<h2>JavaScript Array Sort</h2>
<p>The highest number is <span id="demo"></span>.</p>
最佳答案
因为您在实际定义之前尝试使用Array.myArrayMax
。
var points = [40, 100, 1, 5, 25, 10];
var len, max;
Array.prototype.myArrayMax = function() {
len = this.length;
max = -Infinity;
while (len--) {
if (this[len] > max) {
max = this[len];
}
}
return max;
}
console.log(points.myArrayMax());
关于javascript - 为什么下面的原型(prototype)声明不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59192259/