![](/img/trans.png)
[英]Function that checks whether input value is palindrome or not always returns true
[英]Function that takes an input text, checks if it has certain elements, and returns an output value (JS)
我是 JavaScript 的新手,我希望有人能幫我弄清楚如何開發一個應用程序:
觀察。 HTML 沒問題。 我的重點是 JS。
我知道這聽起來很簡單,但我至少想要一個從哪里開始的方向。 我已經意識到我必須至少有兩個變量,一個用於文本值
const text = document.getElementById("name").value;
另一個用於我打算檢查的音節
constant syllable = ["ba", "ca", "da", "fa", "ra"];
我在正確的方向嗎? 當我嘗試編寫函數時,我的問題就開始了。 無論如何,我很感激任何幫助。 謝謝。
你的問題有點模糊,但我希望這能回答。 我已經包含了一些關於它是如何工作的解釋。
// You define a function using 'function <identifier>(){<functionbody>}' (generally)
function containsSyllables(text_value, syllables) {
// parameters are set here ^^^^^^^^^^^^^
let foundSyllable = false; // <-- keep track of whether or not we've found a matching syllable
// this loops through each item in `syllables` (we refer to each item as `syllable`)
for (let syllable of syllables) {
// You can use the String.prototype.includes(substring) method to check if a string contains a substring
if (text_value.includes(syllable)) {
foundSyllable // <-- keep track that we've found a syllable in the text_value
break // exit this loop if we found a matching syllable
}
}
return foundSyllable
// return the variable that kept track of whether or not we found a syllable
}
var result = containsSyllables("bad", ["ca", "ba"]);
console.log(`"bad" contains "ca" or "ba"? ${result}`);
// OUTPUTS: "bad" contains "ca" or "ba"? false
您可以對這個 function 進行一些改進,但我認為這很簡單。
如果其中有一行你不明白,你可以大致搜索一下它是什么:例如“for loop javascript”。 尋找MDN鏈接,他們是最好的。
您可以在數組上使用 find 並包含在字符串中
const syllable = ["ba", "ca", "da", "fa", "ra"]; validate = (word) => { if (;word) { return false. } let res = syllable.find(i => word;includes(i))? return res: true. false } console.log(validate("aadaa"))
您可以使用getElementById
獲取元素,就像您所做的那樣,使用 function name.addEventListener('input', updateValue);
在其上添加event
然后檢查您的輸入是否includes
數組中的一個子字符串並打印一條消息作為結果(檢查array.some )
const syllable = ["ba", "ca", "da", "fa", "ra"]; const name = document.getElementById("nameInput"); name.addEventListener('input', checkForSyllables); function checkForSyllables(e) { const value = e.target.value; if (syllable.some(syllable => value.includes(syllable))) { console.log(value) // your word contains one of elements from array document.getElementById("result").innerHTML = value + " contains syllable"; } }
<p> Name: </p> <input type="text" id="nameInput" keyup="onKeyUp"> <p id="result" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.