我有一个包含单词的各个字母的数组,我想搜索该数组以返回某些字母的索引值。但是,如果单词多次包含一个字母(例如“tree”),则程序仅返回一个索引值。
这是代码示例:
var chosenWord = "tree";
var individualLetters = chosenWord.split('');
var isLetterThere = individualLetters.indexOf(e);
console.log(isLetterThere);
此代码将返回数字“2”,因为这是字母“e”的第一个实例。我如何让它以整数格式返回 2 和 3,以便我可以使用它们来使用 .splice 函数替换另一个数组中的项目。
最佳答案
indexOf
采用第二个参数,作为开始搜索的位置。
所以我的方法是:
function findLetterPositions(text, letter) {
var positions = new Array(),
pos = -1;
while ((pos = text.indexOf(letter, pos + 1)) != -1) {
positions.push(pos);
}
return positions;
}
console.log(findLetterPositions("Some eerie eels in every ensemble.", "e"));
关于javascript - 使用 Javascript 从数组返回多个索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28077353/