我正在嘗試創建一個程式,該程式從 html 中獲取用戶的輸入并通過 for 回圈運行它,然后顯示翻譯后的輸入。問題是輸出只顯示undefined. 應該使用 html 中的按鈕呼叫在輸入框中轉換用戶輸入的函式,但是單擊它不會改變任何內容,并且輸出只是保持“未定義”
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i ) {
for (var j = 0; j < vowels.length; j ) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
console.log(resultArray.join('').toUpperCase());
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = resultArray.join('').toUpperCase();
console.log(resultArray);
}
function translateInput() {
let userInput = document.getElementById('input').value
let translateResult = whaleTalk(userInput);
updateOutput(translateResult);
}
function updateOutput(input) {
document.getElementById('output').innerHTML = input;
}
whaleTalk();
updateOutput();
<!DOCTYPE html>
<head>
<title>Whale Talk Translator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="whaletranslator.css" rel="stylesheet" type="text/css" />
<style>
</style>
</head>
<body>
<header style="color: white;">Whale Talk Translator </header>
<h2>Input anything you want into the box below and hit the button to translate it.</h1>
<div class="translatorBox">
<input value="" id="input" type="text" class="inputBox" placeholder="Text to translate">
<br>
<div class="container">
<div class="center">
<button class="translateButton" onclick="updateOutput()">Translate</button>
</div>
</div>
<div class="container">
<div class="center">
<button class="reloadButton" onClick="window.location.reload();">Reload</button>
</div>
</div>
</div>
<p style="padding: 2em">Translated input:</p>
<div class="output">
<p id="output"></p>
</body>
<script src="whaletranslator.js" type="text/javascript"></script>
</html>
uj5u.com熱心網友回復:
您的函式回傳 undefined 因為您沒有從中回傳任何內容。嘗試這個:
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i ) {
for (var j = 0; j < vowels.length; j ) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
return resultsArray.join('').toUpperCase()
}
現在,當您的translationResult變數將是您的updateOutput方法將設定為具有 id 'output' 元素的 innerHtml的字串時。您現在可以呼叫,而不是在底部呼叫這兩個方法translateInput()
uj5u.com熱心網友回復:
您沒有滿足方法的引數updateOutput,“未定義”訊息是由于引數未在您的呼叫中定義而引起的
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361526.html
標籤:javascript html
