'Length' Property Undefined while iterating Array

后端 未结 3 894
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 04:00

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 th

相关标签:
3条回答
  • 2020-12-04 04:07

    Instead of error prone hand-written loops for iterating over an array, why not take advantage of the functions that JS provides you - in this case Array.prototype.map:

    function findLongestWord(s) {
        return Math.max.apply(this, s.split(/\s+/).map(function(w) {
            return w.length;
        }));
    }
    

    The Math.max.apply(this, some_array) is the standard JS way of calling Math.max(a, b, c, d, ...) with the given array instead of passing a list of parameters of unknown length.

    In ES2015 you could use the even shorter:

    function findLongestWord(s) {
        return Math.max(...s.split(/\s+/).map((w) => w.length));
    }
    
    0 讨论(0)
  • 2020-12-04 04:15

    You read error wrong :-) not length is undefined, but object where you try get this property - undefined.
    So currentWord is undefined
    because you have wrong loop condition: i<=arrayL,
    when i == arrayL - var currentWord = array[i] is undefined and you get error.

    Just fix it: i < arrayL

    0 讨论(0)
  • 2020-12-04 04:30

    The problem is the bounds of your iteration

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

    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.

    Also, please use var here

    for (var i=0; i < arrayL; i++) {
    
    0 讨论(0)
提交回复
热议问题