高阶功能:阵列过滤器Javasctipt

发布于 2025-01-31 09:12:59 字数 283 浏览 1 评论 0 原文

我有一系列我想过滤的字符串。

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

我只想保留包含字母“ a”的单词。

var wordsWithA = words.filter(function (word) {
  return words.indexOf('a', 4);
  
});

如何使用JavaScript中的索引来完成此操作?

I have an array of strings that I am wanting to filter.

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

I am wanting to keep only the words that include the letter 'a'.

var wordsWithA = words.filter(function (word) {
  return words.indexOf('a', 4);
  
});

how do you accomplish this using indexOf in javascript?

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

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

发布评论

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

评论(3

最冷一天 2025-02-07 09:12:59

返回 -1 ,如果在容器中找不到元素。您应该在每个字符串 word 上使用 indexof ,而不是在数组 words

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') !== -1;
});

console.log(wordsWithA);

indexOf returns -1, if it doesn't find the element in the container. You should use indexOf on each string word and not on the array words:

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];

var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') !== -1;
});

console.log(wordsWithA);

偷得浮生 2025-02-07 09:12:59

尝试

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') > -1;
  
});

try

var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
var wordsWithA = words.filter(function (word) {
  return word.indexOf('a') > -1;
  
});
落墨 2025-02-07 09:12:59

需要两个参数:

  1. 首先是需要搜索的子字符串。
  2. 其次是一个可选的参数,即需要搜索子字符串的位置,其默认值为 0

该方法返回第一次出现 searchString 的索引,如果找到,并返回 -1 否则。

在您的情况下,您可以省略位置参数,并如下执行以下操作:

const words = ["hello", "sunshine", "apple", "orange", "pineapple"],
  wordsWithA = words.filter((word) => word.indexOf("a") !== -1);

console.log(wordsWithA);

String.prototype.indexOf(searchString, position) takes two arguments:

  1. First is the substring that needs to be searched.
  2. Second is an optional argument, that is the position from where the substring needs to be searched, the default value of which is 0.

And the method returns the index of the first occurrence of the searchString, if found, and returns -1 otherwise.

In your case you can omit the position argument and do it as follows:

const words = ["hello", "sunshine", "apple", "orange", "pineapple"],
  wordsWithA = words.filter((word) => word.indexOf("a") !== -1);

console.log(wordsWithA);

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