javascript - 为什么下面的原型(prototype)声明不起作用?

标签 javascript arrays prototype

我已经声明了数组原型(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/

相关文章:

c - 这个排序算法的大O

javascript - 数字数组数组的接口(interface)

java - 了解来自 Java 和 C++ 背景的 Javascript 原型(prototype)

javascript - 在同一个声明中创建javascript函数和原型(prototype)定义?

javascript - Angular js错误: [$injector:unpr]

javascript - 类声明问题

javascript - 使用 JavaScript 打印 HTML

php - 如何在 php 中显示表架构查询中的数组

JavaScript:将 "this"分配给原型(prototype)函数

javascript - 在三个 js 中加载 JSON 模型上的动画颜色