JavaScript搜索一个以某个值开头的值的数组

发布于 2025-02-01 08:53:09 字数 184 浏览 4 评论 0原文

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

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

因此,搜索“ ABCD”将在上述返回。

我一直在玩,但这似乎只能检查全部价值。 另外,我认为startswith我不认为会检查字符串而不是数组中的值吗?

I am looking for a way to search an array to see if a value is present that starts with the search term.

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

So a search for 'abcd' would return true on the above.

I have been playing about with includes, but that only seems to check the full value.
Also, startsWith I dont think will work as I believe that checks a string and not values in an array??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流年已逝 2025-02-08 08:53:09

您可以使用 函数允许您在参数中传递自定义功能,该功能将在每个值上进行测试。这样,您可以按照您的意愿在数组的每个值上使用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

如果要返回truefalse而不是值,则可以检查返回的值是否不同于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

You can use the find() function which allows you to pass a custom function in parameter that will be tested on each value. This way you can use startsWith() on each value of the array as you intended to do.

Example:

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

If you want to return true or false instead of the value, you can check if the returned value is different from undefined.

function findStartWith(arg) {
  return !!array1.find(value => {
    return arg.startsWith(value);
  }) !== undefined;
}

The same snippet with a boolean:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文