gpt4 book ai didi

javascript - 为什么这段 JavaScript 代码没有执行?

转载 作者:行者123 更新时间:2023-11-28 05:37:10 28 4
gpt4 key购买 nike

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

<!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>

最佳答案

您只需将数组传递给函数即可。您正在传递 employess

object
<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>

或者,如果您想传递员工的对象,您可以像employees.employees一样访问

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;
}

关于javascript - 为什么这段 JavaScript 代码没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267944/

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