高阶功能:阵列过滤器Javasctipt
我有一系列我想过滤的字符串。
var words = ['hello', 'sunshine', 'apple', 'orange', 'pineapple'];
我只想保留包含字母“ a”的单词。
var wordsWithA = words.filter(function (word) {
return words.indexOf('a', 4);
});
如何使用JavaScript中的索引来完成此操作?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
返回
-1
,如果在容器中找不到元素。您应该在每个字符串 word 上使用indexof
,而不是在数组words
:indexOf
returns-1
, if it doesn't find the element in the container. You should useindexOf
on each stringword
and not on the arraywords
:尝试
try
需要两个参数:
0
。该方法返回第一次出现
searchString
的索引,如果找到,并返回-1
否则。在您的情况下,您可以省略
位置
参数,并如下执行以下操作:String.prototype.indexOf(searchString, position) takes two arguments:
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: