数组迭代时'Length'属性未定义 [英] 'Length' Property Undefined while iterating Array

查看:99
本文介绍了数组迭代时'Length'属性未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迭代数组以找到最长的字符串.每次收到错误Cannot read property length of undefined. Console.log告诉我正在读取和理解数组的长度以及字符串的长度,因此我无法理解哪里存在未定义的属性.实际上,我试图将程序的原始长度增加了将近三倍,以确保定义了每个变量,但仍然不好.任何帮助将不胜感激.

Iterating an array to find the longest string. Each time I've received the error Cannot read property length of undefined. Console.log tells me that the length of the array as well as the length of the string are being read and understood so I cannot understand where there is an undefined property. In fact, I've just about tripled the original length of the program trying to make sure every variable is defined but still no good. Any help would be greatly appreciated.

function findLongestWord(str) {
  var longest = 0;
  var array = str.split(" ");
  var arrayL = array.length;
  for (i=0; i<=arrayL; i++) {
    var currentWord = array[i];
    var currentL = currentWord.length;
    if (currentL > longest) {
      currentL = longest;
    };
  };
  return longest;
};

findLongestWord("The quick brown fox jumped over the lazy dog");

虽然以下答案确实解决了问题,但我也只想为以后可能会在Google上搜索此线程的人提及,我还必须将自longest以来的最终if statementcurrentL = longest;交换为longest = currentL >是我最终要返回的东西.

While the below answers did solve the issue, I also just wanted to mention for people that may later google this thread that I also had to swap my final if statement from currentL = longest; to longest = currentL since longest is what I was ultimately returning.

推荐答案

问题是迭代的局限性

for (i=0; i<=arrayL; i++) {

请注意,您将需要执行array [array.length]来执行此操作,并且该操作始终是未定义的,因为10个项的数组中的第10个项是[9],[10]是未定义的.

Note that you are going to be looking for array[array.length] doing this and that will always be undefined because the 10th item in an array of 10 items is [9], [10] is undefined.

另外,请在此处使用var

Also, please use var here

for (var i=0; i < arrayL; i++) {

这篇关于数组迭代时'Length'属性未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆