gpt4 book ai didi

javascript - 如何从外部 js 文件中的 JSON 数组获取变量?

转载 作者:行者123 更新时间:2023-12-01 03:48:10 26 4
gpt4 key购买 nike

我有一个外部 JS 文件,其中包含 JSON 数组和函数,可帮助我选择一组随机变量。当我尝试在主 HTML 文件中生成结果时,p 标记中没有显示任何内容。我是否不匹配任何对象或变量?

正文部分 HTML 文件的简短示例

<p id="result"></p>
<script src="myJSfile.js" type="text/javascript">
<script language="javascript" type="text/javascript">
document.getElementById("result").innerHTML = lottery(selected.name + selected.age);
</script>

外部 JS 文件的简短示例

function lottery() {
var from, to, selected=new Array();
var person=
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];
if (arguments[0] == "all") {
from=0;
to=person.length;
}
else {
from=Math.floor(Math.random()*3);
to=Math.floor(Math.random()*3+1);
}
for (i=0; i<to; i++) {
selected[i]=person[from];
from=(from+1)%3;
}
return selected;
}

最佳答案

您的 fromtoselected 变量在函数外部不可见,只需将此行 var from, to, selected =new Array(); 脱离函数,它应该可以工作。

全部

var from, to, selected = new Array();
lottery('all');
for(var k = 0; k < selected.length; k++){
document.getElementById("result").innerHTML += selected[k].name + " " + selected[k].age+'<br />';
}

function lottery() {
var person =
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];

if (arguments[0] == "all") {
from = 0;
to = person.length;
}
else {
from = Math.floor(Math.random()*3);
to = Math.floor(Math.random()*3+1);
}

for (i = 0; i < to; i++) {
selected[i] = person[from];
from = (from+1)%3;
}

return selected;

}
<p id="result"></p>

随机

var from, to, selected = new Array();
lottery('all');
for(var k = 0; k < selected.length; k++){
document.getElementById("result").innerHTML += selected[k].name + " " + selected[k].age+'<br />';
}

function lottery() {
var person =
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];

if (arguments[0] == "alla") {
from = 0;
to = person.length;
}
else {
from = Math.floor(Math.random()*3);
to = Math.floor(Math.random()*3+1);
}

for (i = 0; i < to; i++) {
selected[i] = person[from];
from = (from+1)%3;
}

return selected;

}
<p id="result"></p>

关于javascript - 如何从外部 js 文件中的 JSON 数组获取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429880/

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