我有一個要過濾的字串陣列。
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
我只想保留包含字母“a”的單詞。
var wordsWithA = words.filter(function (word) {
return words.indexOf('a', 4);
});
你如何在 javascript 中使用 indexOf 來實作這一點?
uj5u.com熱心網友回復:
indexOf-1如果在容器中找不到元素,則回傳。您應該indexOf在每個字串上使用,word而不是在陣列上使用words:
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
return word.indexOf('a') !== -1;
});
console.log(wordsWithA);
uj5u.com熱心網友回復:
嘗試
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
return word.indexOf('a') > -1;
});
uj5u.com熱心網友回復:
String.prototype.indexOf(searchString, position)有兩個引數:
- 首先是需要搜索的子字串。
- 第二個是可選引數,即需要搜索子字串的位置,默認值為
0.
searchString如果找到,該方法回傳第一次出現的索引,-1否則回傳。
在您的情況下,您可以省略position引數并按如下方式執行:
const words = ["hello", "sunshine", "apple", "orange", "pineapple"],
wordsWithA = words.filter((word) => word.indexOf("a") !== -1);
console.log(wordsWithA);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479508.html
標籤:javascript 数组 筛选 指数 高阶函数
上一篇:設定多個標簽值-尋找更好的方法
下一篇:在節點js服務器中列印陣列
