简体   繁体   English

我怎样才能得到数组 indexOf 元素包括值

[英]How can i get array indexOf element includes value

How can i get array indexOf element includes value Like我怎样才能得到数组 indexOf 元素包括值喜欢

var a = ["one","two","xx?ee"]; 

a.indexOf("?"); //i want to get indexOf element xx?ee

Use Array.findIndex and String.includes使用Array.findIndexString.includes

 var a = ["one","two","xx?ee"]; var ndx = a.findIndex(e => e.includes("?")); console.log(ndx);

Keep in mind that this will return the first match only.请记住,这将仅返回第一场比赛。

You can use reduce .您可以使用reduce This code will return an array , assuming that there can be multiple words wich contains ?此代码将返回一个数组,假设可以包含多个单词? . . So this aray will contain the index of all those words.所以这个数组将包含所有这些词的索引。

 var a = ["one", "two", "xx?ee", "11?ee"]; function getIndex(key) { return a.reduce((acc, curr, index) => { if (curr.includes(key)) { acc.push(index) } return acc; }, []) } console.log(getIndex('?'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM