[英]Why do I get "Uncaught TypeError: Cannot read property 'length' of undefined(…)"?
[英]Why do I get "TypeError: Cannot read property 'length' of undefined" when using length method
我寫了一個返回最長單詞的 function
const longestWord = (phrase) => {
const arr = phrase.split(" ");
let longest;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length < arr[i+1].length){
longest = arr[i+1]
[arr[i]] = [arr[i+1]]
}
}
return longest;
}
let longWhich = longestWord("Web Development Tutorial");
console.log(longWhich);
但我收到以下錯誤:
if (arr[i].length提前致謝
問題是一個i
指向最后一個元素,然后i+1
undefined
有多種方法可以解決此問題是掃描數組中最大的字符串,一種方法如下
function findLargestElement(phrase) {
const arr = phrase.split(" ");
let max, len = arr.length, i=0;
max = i
// here scan the largest element of array
for (let j = i + 1; j < len; j++) {
if (arr[max].length < arr[j].length) {
max = j
}
}
return arr[max]
}
console.log(findLargestElement('i am adnan'))//adnan
這是另一種方法,使用Array.prototype.reduce()
:
function findLargestElement(txt) { return txt.split(/\W+/)//.reduce((a,c)=>a.length>c.length?a:c); } console.log(findLargestElement('My name is Carsten and I like JavaScript - much more than Java.')) // JavaScript
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.