gpt4 book ai didi

javascript - 遍历JavaScript对象

转载 作者:行者123 更新时间:2023-12-03 07:18:47 26 4
gpt4 key购买 nike

无法访问对象。他们正在打印未定义。救命!我需要代码来打印学生姓名。

let students = [
{name: 'Remy', cohort: 'Jan'},
{name: 'Genevieve', cohort: 'March'},
{name: 'Chuck', cohort: 'Jan'},
{name: 'Osmund', cohort: 'June'},
{name: 'Nikki', cohort: 'June'},
{name: 'Boris', cohort: 'June'}
];



function objPrint() {
for (var i=0; i<students.length; i++) {
console.log("Name: " + students[i][0] + " Cohort: " + students[i][1])
}
}

最佳答案

做这样的事情:

let students = [
{name: 'Remy', cohort: 'Jan'},
{name: 'Genevieve', cohort: 'March'},
{name: 'Chuck', cohort: 'Jan'},
{name: 'Osmund', cohort: 'June'},
{name: 'Nikki', cohort: 'June'},
{name: 'Boris', cohort: 'June'}
];



function objPrint() {
for (var i=0; i<students.length; i++) {
// Can also use students[i]['name'] , students[i]['cohort']
// using lodash.js _.get(students, [i, 'name'], 'default value');
// using new destructuring let {name, cohort} = students[i] then console.log("name: "+ name + " Cohort: "+cohort);
console.log("Name: " + students[i].name + " Cohort: " + students[i].cohort);
}
}

关于javascript - 遍历JavaScript对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52595835/

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