Javascript 在数组中搜索以特定值开头的值

Javascript search an array for a value starting with a certain value

我正在寻找一种方法来搜索数组以查看是否存在以搜索词开头的值。

const array1 = ['abc','xyz'];

因此,搜索 'abcd' 将 return 为真。

我一直在研究包含,但这似乎只能检查完整值。 另外,我认为 startsWith 不会起作用,因为我相信它会检查字符串而不是数组中的值??

您可以使用 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

如果您想 return truefalse 而不是值,您可以检查 returned 值是否与 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