我正在尋找一種方法來搜索陣列以查看是否存在以搜索詞開頭的值。
const array1 = ['abc','xyz'];
因此,在上面搜索“abcd”將回傳 true。
我一直在玩包含,但這似乎只能檢查全部價值。另外,我認為startsWith不會起作用,因為我相信檢查字串而不是陣列中的值?
uj5u.com熱心網友回復:
您可以使用find()允許您在引數中傳遞自定義函式的函式,該函式將對每個值進行測驗。這樣您就可以startsWith()按照您的意圖使用陣列的每個值。
例子:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
});
}
console.log(findStartWith("hello")); // undefined
console.log(findStartWith("abcd")); // abc
console.log(findStartWith("xyzz")); // xyz
如果要回傳trueorfalse而不是值,可以檢查回傳的值是否不同于undefined.
function findStartWith(arg) {
return !!array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
帶有布林值的相同片段:
const array1 = ['abc','xyz'];
function findStartWith(arg) {
return array1.find(value => {
return arg.startsWith(value);
}) !== undefined;
}
console.log(findStartWith("hello")); // false
console.log(findStartWith("abcd")); // true
console.log(findStartWith("xyzz")); // true
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480944.html
標籤:javascript 数组 搜索 以。。开始
上一篇:通過Link傳遞id到getServerSideProps:nextjs
下一篇:如何在柏樹中傳遞定位器作為引數?
