如何在数组中找到包含我正在寻找的内容的索引或元素?
当我尝试使用includes()时
m.includes()不是函数
我已经安装了NPM的array-includes,但我仍然想不出怎么做。我想要的例子:
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.我试过:
pinmsgs = pinmsgs.filter(includes(pinmsgs, 'countdownTill'))这是一个错误:
(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,它仍然会输出苹果
发布于 2019-05-05 12:50:26
如果要查找元素,可以使用find。如果要查找索引,则为findIndex。
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)
发布于 2019-05-05 12:51:53
有很多功能你可以使用
indexOf,如果找不到,返回索引或-1。const a = ['orange', 'apple', 'kiwi'];
console.log(a.indexOf('apple'));
// 1filter返回与特定条件匹配的项的数组。const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.filter(x => x === 'apple'));
// ['apple', 'apple']find返回匹配项的第一个值,如果没有找到,则返回未定义的返回值。const a = ['orange', 'apple', 'kiwi', 'apple'];
console.log(a.find(x => x === 'apple'));
// applehttps://stackoverflow.com/questions/55992053
复制相似问题