为什么这个javascript代码没有执行?

时间:2016-09-01 09:37:33

标签: javascript

我正在尝试使用 myFunction()执行对象数组,但它无效。我错过了什么?我想显示数组员工的所有对象。



<!DOCTYPE html>
<html>
<body>

<div id="id01"></div>
<div id="id02"></div>
<script>
myFunction({

"employees":[
   {"firstName":"John","lastName":"Doe" },
   {"firstName":"Anna","lastName":"Smith" },
   {"firstName":"Peter","lastName":"Jones" }
            ]

});

 function myFunction(employees) {
        var out = "";
        var i;
        for(i = 0; i<employees.length; i++) {
            out += '<a href="' + employees[i].firstName + '">' +
            employees[i].lastName + '</a><br>';
        }
        document.getElementById("id01").innerHTML = out;
    }
    

</script>

</body>
</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

您只需将array传递给该函数即可。您正在通过object

employess
<script>
myFunction([
   {"firstName":"John","lastName":"Doe" },
   {"firstName":"Anna","lastName":"Smith" },
   {"firstName":"Peter","lastName":"Jones" }
            ]

);

 function myFunction(employees) {
        var out = "";
        var i;
        for(i = 0; i<employees.length; i++) {
            out += '<a href="' + employees[i].firstName + '">' +
            employees[i].lastName + '</a><br>';
        }
        document.getElementById("id01").innerHTML = out;
    }


</script>

或者,如果您想通过object员工,您可以像雇员一样访问

myFunction({

        "employees": [
           { "firstName": "John", "lastName": "Doe" },
           { "firstName": "Anna", "lastName": "Smith" },
           { "firstName": "Peter", "lastName": "Jones" }
        ]

    });

    function myFunction(employees) {
        var out = "";
        var i;
        for (i = 0; i < employees.employees.length; i++) {
            out += '<a href="' + employees.employees[i].firstName + '">' +
            employees.employees[i].lastName + '</a><br>';
        }

        document.getElementById("id01").innerHTML = out;
    }

答案 1 :(得分:0)

做你想做的事的好方法:

myfunction([
       {"firstName":"John","lastName":"Doe" },
       {"firstName":"Anna","lastName":"Smith" },
       {"firstName":"Peter","lastName":"Jones" }
                ]);
    function myFunction(employees) {
            var out = "";
            var i;
            for(i = 0; i<employees.length; i++) {
                out += '<a href="' + employees[i].firstName + '">' +
                employees[i].lastName + '</a><br>';
            }
            document.getElementById("id01").innerHTML = out;
    }

答案 2 :(得分:0)

我为你制作了一段代码片段。

主要问题是你没有在函数中输入一个数组而是一个对象。我也重构了你的代码。

var employees = [ {"firstName":"John","lastName":"Doe" }, {"firstName":"Anna","lastName":"Smith" }, {"firstName":"Peter","lastName":"Jones"} ];

myFunction(employees);

function myFunction(employees) {
  var out = "";
  for(var i = 0; i < employees.length; i++) {
    out += '<a href="' + employees[i].firstName + '">' + employees[i].lastName + '</a><br>';
  }
  document.getElementById("id01").innerHTML = out;
}
<div id="id01"></div>
<div id="id02"></div>

真诚的你