gpt4 book ai didi

javascript - 如何将数组链接到 html 中的 javascript 函数?

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:04 25 4
gpt4 key购买 nike

大家好,我是 Javascript 的新手,我对如何实际调用函数感到很困惑。我不确定为什么这不起作用,希望能提供一些意见。

我的 HTML :

<html>
<head>
<script type="text/javascript" src="problem2.js"></script>
</head>
<body>
<INPUT TYPE="button" NAME="Answer" VALUE="Click to see Answer" onClick="MyFunction(array);">
<div id="answer"></div>
</body>
</html>

我的 JavaScript:

var array = [3, 1, 1, 'a', 'a', 3, 'b', 'f', 'a', 1, 'a'];

function MyFunction(array) {
var counter = 0,
amount = 1,
highest;

for (var i=0; i<array.length; i++) {
for(var j=i; j<array.length;j++) {
if (array(i) ===array(j)){
counter++;
}
if(counter>amount){
amount=counter;
highest=array[i];
}
}
counter = 0;
}
document.getElementById("answer").innerHTML(highest + " " + amount + times");
}

最佳答案

你的函数有几个错误,首先要访问一个数组项,你应该使用方括号 [] 而不是 (),例如:

if (array[i] === array[j]){
counter++;
}

您在下一行中遗漏了一个双引号 ",同样要使用 innerHTML 分配 HTML,您应该在它后面加上 = :

document.getElementById("answer").innerHTML(highest + " " + amount + times");

应该是:

document.getElementById("answer").innerHTML = highest + " " + amount + "times";

而且您不必从 HTML 传递数组,因为数组已经在 J​​S 代码中定义,所以只需使用它:

<INPUT TYPE="button" NAME="Answer" VALUE="Click to see Answer" onClick="MyFunction();">

//Define function without argument
function MyFunction() {
//your code here
}

希望这对您有所帮助。


工作片段

var array = [3, 1, 1, 'a', 'a', 3, 'b', 'f', 'a', 1, 'a'];

function MyFunction() {
var counter = 0;
var amount = 1;
var highest;
var i;
for (i=0; i<array.length; i++)
{
for(var j=i; j<array.length;j++){
if (array[i] === array[j]){
counter++;
}

if(counter>amount){
amount=counter;
highest=array[i];
}
}
counter = 0;
}

document.getElementById("answer").innerHTML = highest + " " + amount + "times";
}
<INPUT TYPE="button" NAME="Answer" VALUE="Click to see Answer" onClick="MyFunction();">
<div id="answer"></div>

关于javascript - 如何将数组链接到 html 中的 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35477216/

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