访问对象时遇到麻烦。他们正在打印未定义。救命!我需要代码来打印学生姓名。
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])
}
}
答案 0 :(得分:3)
您正在访问项目,就好像它是一个数组一样。但实际上它是一个对象数组。
顶层,已经获取了当前项目,只需使用点或括号符号访问键即可获取值。
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'}
];
students.forEach((item) => {
//console.log(`Name - ${item.name} :: Cohort - ${item.cohort}`);
console.log('Name - ' + item.name + " :: Cohort - " + item.cohort );
});
答案 1 :(得分:3)
执行以下操作:
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);
}
}
答案 2 :(得分:1)
您需要这样调用键/属性:students[i].name
,然后调用方法objPrint()
来打印值。
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].name + " Cohort: " + students[i].cohort)
}
}
objPrint();
答案 3 :(得分:0)
对象的属性是通过点表示法而不是带数字的括号来访问的。 所以你应该这样做
students[i].name
答案 4 :(得分:0)
尝试..of:
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'}
]
// returns an object as a student
for(let student of students) {
console.log(`Name: ${student.name} Cohort: ${student.cohort}`)
}
这种方法的优点
.foreach()
不同,它可以中断,继续和返回也..使用反引号来避免老式的字符串连接方式-看起来更好:)
答案 5 :(得分:0)
尝试一下:
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 sobjPrint() {
for (var i in students) {
if (students.hasOwnProperty(i)) {
console.log("Name: " + students[i].name + " Cohort: " + students[i].cohort)
}
}
}