使用下面的陣列,我想搜索第一個字母,假設在同一個矩陣中有幾個單詞,它必須在每個單詞中搜索,如果找到它應該回傳一個陣列
例子
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
]
如果它匹配 "sh" 它應該搜索每個單詞并回傳
["Shutter Island", "The Truman Show"] but not The Gold Rush
如果它匹配“獅子”它應該搜索每個單詞并回傳
["the lions of teranga"]
uj5u.com熱心網友回復:
這是結合forEach和的解決方案之一RegEx
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
const filteredData = []
data.forEach(sentence => {
let words = sentence.split(" ")
words.forEach((word,index) => {
if(word.match(/^lions?\w/gi)) {
filteredData.push(sentence)
}
})
})
console.log(filteredData)
uj5u.com熱心網友回復:
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
]
inputData = "lions"
let a = data.filter(e => {
str = e.toLowerCase()
if (str.match(inputData.toLowerCase())){
return e
}
})
console.log(a)
這里過濾器回傳回傳 true 的物件。在這里,您可以按任何單詞或字符搜索并以陣列形式回傳。
uj5u.com熱心網友回復:
//your data array
const data= [
"the lions of teranga",
"tiger woods",
"The Truman Show",
"Shutter Island",
"The Gold Rush",
];
//your search letters,if it will be the same use const instead of var
var search="sh";
//make your search case insensitive
search=search.toLowerCase()
//use for loop to go through every sentence
for(var counter=0;counter<data.length;counter )
{
//get the array of words
var arrayOfWords=data[counter].match(/\b(\w )\b/g);
//use for loop to go through every word
for(var counter2=0;counter2<arrayOfWords.length;counter2 )
{
//make word case insensitive
var tempWord=arrayOfWords[counter2].toLowerCase();
//check if the search length does not exid your actuall word
if(search.length<=tempWord.length)
{
//check if first letters match
if(tempWord.slice(0,search.length==search)
{
//first letters match, you can put your logic here
}
else
{
//no match
}
}
else
{
//search exids word
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478723.html
標籤:javascript 数组 搜索
下一篇:使用按鈕在陣列中顯示不同的文本值
