首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用来自npm的数组找到数组中的元素

使用来自npm的数组找到数组中的元素
EN

Stack Overflow用户
提问于 2019-05-05 12:42:50
回答 2查看 45关注 0票数 0

如何在数组中找到包含我正在寻找的内容的索引或元素?

当我尝试使用includes()

m.includes()不是函数

我已经安装了NPM的array-includes,但我仍然想不出怎么做。我想要的例子:

代码语言:javascript
复制
Make an array of strings eg. ['apple', 'orange', 'kiwi']
Check each of the elements for If they contain 'orange'
Have it return either the element itself, or the index of the element in the 
array.

我试过:

代码语言:javascript
复制
pinmsgs = pinmsgs.filter(includes(pinmsgs, 'countdownTill'))

这是一个错误:

代码语言:javascript
复制
(node:3256) UnhandledPromiseRejectionWarning: TypeError: fn is not a function
at Map.filter (C:\Users\oof\Desktop\VVbot - kopie (2) - kopie\node_modules\d
iscord.js\src\util\Collection.js:289:11)
at message.guild.channels.find.fetchPinnedMessages.then (C:\Users\oof\Deskto
p\VVbot - kopie (2) - kopie\bot.js:54:37)
at process._tickCallback (internal/process/next_tick.js:68:7)

我也需要它的工作,当我只投入了我正在寻找的一部分-例如。如果我寻找appl,它仍然会输出苹果

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-05 12:50:26

如果要查找元素,可以使用find。如果要查找索引,则为findIndex

代码语言:javascript
复制
const array = ['apple', 'orange', 'kiwi'],
      item = "orange";

const found = array.find(a => a.includes(item))
const index = array.findIndex(a => a.includes(item))

// if you want to find if item exists in the array
const fullMatchIndex = array.indexOf(item)

console.log(found)
console.log(index)
console.log(fullMatchIndex)

票数 0
EN

Stack Overflow用户

发布于 2019-05-05 12:51:53

有很多功能你可以使用

  • 使用indexOf,如果找不到,返回索引或-1。
代码语言:javascript
复制
const a = ['orange', 'apple', 'kiwi'];
console.log(a.indexOf('apple'));
// 1
  • 可以使用filter返回与特定条件匹配的项的数组。
代码语言:javascript
复制
const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.filter(x => x === 'apple'));
// ['apple', 'apple']
  • 可以使用find返回匹配项的第一个值,如果没有找到,则返回未定义的返回值。
代码语言:javascript
复制
const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.find(x => x === 'apple'));
// apple
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55992053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档