[英]how to fix 'Cannot read property of undefined'?
I'm trying to determine which object in an array has the longest name and logging that object to the console.我正在尝试确定数组中哪个对象的名称最长,并将该对象记录到控制台。
I can't seem to access the length of the name property in my 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"}
but I get an error stating it cannot read property '.length'但我收到一条错误消息,指出它无法读取属性“.length”
You could use你可以用
let longest = Number.MIN_SAFE_INTEGER;
to set longest to the smallest safe integer , since minimum length is equal to 0 (number elements of elements is equal to zero)将最长设置为最小的安全整数,因为最小长度等于 0(元素的元素数等于零)
Or simply set it to 0
:或者简单地将其设置为
0
:
let longest = 0
One tiny 'remark' - as @Jaromanda X mentioned in a comment - let
without providing a value will result in undefined
, eg:一个小小的“备注” - 正如@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
Thanks for the help guys!感谢您的帮助! By changing longest to the first object and starting my loop at 1 I was able to call the correct properties.
通过将最长更改为第一个对象并从 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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.