繁体   English   中英

Function 接受输入文本,检查它是否具有某些元素,并返回 output 值 (JS)

[英]Function that takes an input text, checks if it has certain elements, and returns an output value (JS)

我是 JavaScript 的新手,我希望有人能帮我弄清楚如何开发一个应用程序:

  1. 按下按钮时从HTML 输入中获取文本值;
  2. 检查该文本值是否包含某些音节(例如,它是否包含音节“ba”、“ca”和“da”);
  3. HTML output返回一个值,无论它是否有音节。

观察。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM