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

时间:2017-04-15 18:42:10

标签: javascript html json

我有一个包含JSON数组的外部JS文件,函数可以帮我选择一组随机变量。当我尝试在主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;
   }

2 个答案:

答案 0 :(得分:2)

您的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>

答案 1 :(得分:0)

我已对您的代码进行了一些更改,请检查,这应该有效

Monad

并在您的外部js中

<p id="result"></p>
<script src="stackoverflow.js" type="text/javascript">
<script>
 (function() {
   document.getElementById("result").innerHTML = lottery('all');
 })();
</script>