得到"未定义"将对象添加到新字符串时

时间:2018-04-24 09:19:24

标签: javascript arrays object

我有一个对象数组(学生姓名,成就等等),我想添加任何名称为" Jody" (例如)在我创建的新空数组中。 但是,当我尝试仅打印新对象数组的名称时,我得到了undefined。 注意:我不能使用let,const等..

我在这里缺少什么想法?

var student;
var newStudents = [];
var students = [{
    name: 'Odelia',
    track: 'Accounting',
    achievements: '26',
    points: '2260'
}, {
    name: 'Jody',
    track: 'Web Design',
    achievements: '12',
    points: '890'
}, {
    name: 'Yann',
    track: 'Javascript',
    achievements: '10',
    points: '2266'
}, {
    name: 'Max',
    track: 'Marketing',
    achievements: '13',
    points: '1010'
}, {
    name: 'Jody',
    track: 'iOS',
    achievements: '9',
    points: '1002'
}, ]

for (var i = 0; i < students.length; i++) {
    student = students[i];
    if (student.name === 'Jody') {
        newStudents.push(student);
    }
}

console.log(newStudent.name);

输出:

    0: 
      achievements: "12"
      name: "Jody"
      points: "890"
      track: "Web Design"
      __proto__: Object
    1: 
      achievements: "9"
      name: "Jody"
      points: "1002"
      track: "iOS"
      __proto__: Object
      length: 2
      __proto__: Array(0)

    undefined

4 个答案:

答案 0 :(得分:4)

应为newStudent而不是 console.log(newStudents[0].name);

newStudents

此外,List<Developer> developers = session.createQuery("from Developer d " + "left join ProjectDeveloper pd on pd.developer.id = d.id " + "where pd.project.id = " + project.getId()).getResultList(); 是数组。

答案 1 :(得分:0)

您正在尝试在循环外部打印名称。再次交叉检查。

应该是这样的:

for (var i = 0; i < students.length; i++) {
    student = students[i];
    console.log(newStudent.name);
    if (student.name === 'Jody') {
        newStudents.push(student);
    }
}

答案 2 :(得分:0)

试试这个,这对我有用;

echo "Hello World".PHP_EOL;

答案 3 :(得分:0)

@Yann Bohbot,

有两个问题, 1.在console.log()中输入正确的对象名称,即“newStudents”而不是“newStudent”; 2.您需要更改以下行以获取值, 的console.log(newStudents [1]。名称);

你正在使用多维数组,需要以适当的方式迭代......:)