是否有一種簡短的方法可以確定用戶輸入是否以( endsWith()) 陣列中的元素之一結尾?我想檢查用戶輸入是否以以下后綴之一結尾:“ss”、“ll”、“tt”。如果用戶輸入以這些后綴之一結尾,則代碼應提醒訊息“條件滿足”,否則應提醒“條件失敗”。我可以使用簡單的 if 陳述句來完成,如以下代碼所示:
var inp = document.getElementById("inp");
function findingSuffixes(){
if(inp.value.endsWith('ss') || inp.value.endsWith('tt') || inp.value.endsWith('ll')){
alert('condition met')
} else {
alert('condition failed')
}
}
<p>Enter a word:</p>
<input type="text" id="inp">
<button onclick="findingSuffixes()">Find out</button>
但這有點繞。
我試圖從不同的角度接近它。我創建了一個陣列并將后綴存盤在其中,然后回圈遍歷該陣列并將array[i]endsWith作為引數傳遞給方法,但它沒有按預期作業。
var inp = document.getElementById("inp");
suffixes = ["ss", "tt", "ll"];
function findingSuffixes(){
for(var i=0; i < suffixes.length; i ){
if(inp.value.endsWith(suffixes[i])){
alert("condition Met")
} else {
alert("condition failed")
}
}
}
<p>Enter a word:</p>
<input type="text" id="inp">
<button onclick="findingSuffixes()">Find out</button>
TL'DR:有沒有一種簡短的方法來檢查用戶輸入是否以陣列中的一個元素結尾?
uj5u.com熱心網友回復:
您的代碼的問題在于它alert仍然在回圈中發出while。您只希望它在確定知道時宣告“滿足”或“失敗”。我調整了代碼以展示如何做到這一點。break一旦我們滿足條件,我就退出回圈,因為不需要進一步查看。
var inp = document.getElementById("inp");
var suffixes = ["ss", "tt", "ll"];
function findingSuffixes(){
var msg = "condition failed";
for(const suffix of suffixes){
if (inp.value.endsWith(suffix)){
msg = "condition Met";
break; // no need to continue in the loop
}
}
alert(msg);
}
<p>Enter a word:</p>
<input type="text" id="inp">
<button onclick="findingSuffixes()">Find out</button>
uj5u.com熱心網友回復:
正如@Barmar 提到的,你最好使用 .some()
var inp = document.getElementById("inp"),
sfs = ["ss", "tt", "ll"];
function findingSuffixes() {
alert(sfs.some(sf => inp.value.endsWith(sf)) ? "Condition met"
: "Condition failed");
}
<p>Enter a word:</p>
<input type="text" id="inp">
<button onclick="findingSuffixes()">Find out</button>
uj5u.com熱心網友回復:
您可以使用正則運算式并測驗此運算式中的字串。
/(ll|ss|tt)$/
( ) a group
ll|ss|tt alternatives with ll ss or tt
$ followd by an end of string
function findingSuffixes() {
if (/(ll|ss|tt)$/.test(inp.value)) {
console.log('condition met');
} else {
console.log('condition failed');
}
}
const inp = document.getElementById("inp");
<p>Enter a word:</p>
<input type="text" id="inp">
<button onclick="findingSuffixes()">Find out</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/399551.html
標籤:javascript 数组 循环 以。。结束
上一篇:Insights直播回顧——手語服務,助力溝通無障礙
下一篇:回圈回傳訊息取決于您鍵入的字符數
