如何修复“无法读取未定义的属性”?

时间:2019-04-30 21:35:11

标签: javascript arrays object if-statement

我试图确定数组中哪个对象的名称最长,并将该对象记录到控制台。

我似乎无法在if语句中访问name属性的长度。

const instructorWithLongestName = function(instructors) {
  let longest;
  for (let i = 0; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.length) {
      longest = instructors[i];
    }
  }
  return longest;
};

console.log(instructorWithLongestName([
  {name: "Samuel", course: "iOS"},
  {name: "Jeremiah", course: "Web"},
  {name: "Ophilia", course: "Web"},
  {name: "Donald", course: "Web"}
]));
console.log(instructorWithLongestName([
  {name: "Matthew", course: "Web"},
  {name: "David", course: "iOS"},
  {name: "Domascus", course: "Web"}
]));

I expect the output of
{name: "Jeremiah", course: "Web"}
{name: "Domascus", course: "Web"}

但是我收到一条错误消息,指出它无法读取属性'.length'

2 个答案:

答案 0 :(得分:0)

您可以使用

let longest = Number.MIN_SAFE_INTEGER;

设置最长为smallest safe integer,因为最小长度等于0(元素的元素个数等于零)
或直接将其设置为0

let longest = 0

一个微小的“备注”-如评论中提到的@Jaromanda X-let,如果不提供值,将导致undefined,例如:

let test1;
let test2 = 'some random string';
let test3 = 4;

// comments represent output of corresponding command  
console.log(test1); // undefined
console.log(test2); // some random string
console.log(test3); // 4

答案 1 :(得分:0)

感谢帮助人员!通过将最长的对象更改为第一个对象并从1开始循环,我可以调用正确的属性。

const instructorWithLongestName = function(instructors) {
  let longest = instructors[0];
  for (let i = 1; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.name.length) {
      longest = instructors[i];
    }
  }
  return longest;
};