[英]Source of “undefined” showing in console
Javascript 初學者在這里。 這個 function 應該顯示英文字母表中任何給定字母的 position。 它似乎運行良好,但隨着結果,我得到一個未定義的錯誤。 這是從哪里來的?
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
console.log('Position in the alphabet is: ' + i);
break;
}
}
};
console.log(position("Z"));
改變:
console.log(position("Z"));
至:
position("Z");
Function position 沒有返回任何東西——這就是你變得不確定的原因。
您不會從position(...)
function 返回任何值。 要修復undefined
的錯誤,如果沒有找到結果,您可能希望返回 null,如示例:
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
return 'Position in the alphabet is: ' + i;
}
}
return null;
};
console.log(position("Z"));
您在控制台中看到的undefined
根本不是錯誤。 相反,它是最后一行代碼中console.log()
語句的結果,正如@Russ 所提到的。 它正在記錄執行position("Z")
后收到的內容-實際上是 nothing 或undefined
。
如果您希望能夠對 function 的 output 使用console.log()
,您可以讓它return
一個字符串。 這也將消除break;
在你的for
循環中聲明。 您可能還包括“未找到”類型的默認語句,以防止出現實際錯誤。 (@Dorado 的null
默認是一個不錯的選擇。)以下是我對您的代碼的建議:
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
return('Position in the alphabet is: ' + i);
}
}
return 'Character not found in the alphabet!';
};
console.log(position("Z"));
這將為您提供所需的單個console
output,從控制台中刪除undefined
,並允許您在其他代碼中使用此 function。
您的 function 可能只是這樣:
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
function position=(letter)=> {
console.log(`Position in the alphabet is: ${alphabet.findIndex(el=>el===letter.toLowerCase())}`)
}
position("Z");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.