简体   繁体   English

使用Javascript从数组返回多个索引值

[英]Returning multiple index values from an array using Javascript

I have an array containing the individual letters of a word and i want to search the array to return the index values of certain letters. 我有一个包含单词的各个字母的数组,我想搜索该数组以返回某些字母的索引值。 However, if the word contains more a letter more than once (such as 'tree') the programme only returns one index value. 但是,如果单词包含多个字母(例如“ tree”),则该程序仅返回一个索引值。

This is a sample of the code: 这是代码示例:

var chosenWord = "tree";     
var individualLetters = chosenWord.split('');
var isLetterThere = individualLetters.indexOf(e);
console.log(isLetterThere);

this code will return the number '2', as that is the first instance of the letter 'e'. 该代码将返回数字“ 2”,因为这是字母“ e”的第一个实例。 How would i get it to return 2 and 3 in the integer format, so that i could use them to replace items in another array using the .splice function. 我将如何获取它以整数格式返回2和3,以便可以使用它们使用.splice函数替换另一个数组中的项目。

indexOf takes a second parameter, as the position where it should start searching from. indexOf采用第二个参数作为应从其开始搜索的位置。

So my approach would be: 所以我的方法是:

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"));

http://jsfiddle.net/h2s7hk1r/ http://jsfiddle.net/h2s7hk1r/

You could write a function like this: 您可以编写如下函数:

function indexesOf(myWord, myLetter)
{
    var indexes = new Array();
    for(var i = 0; i < myWord.length; i++)
    {
        if(myWord.charAt(i) == myLetter)
        {
            indexes.push(i);
        }
    }
    return indexes;
}
console.log(indexesOf("tree", "e"));

Loop through it as here: 如下循环:

 var chosenWord = "tree"; var specifiedLetter = "e"; var individualLetters = chosenWord.split(''); var matches = []; for(i = 0;i<individualLetters.length;i++){ if(individualLetters[i] == specifiedLetter) matches[matches.length] = i; } console.log(matches); 

An alternative using string methods. 使用字符串方法的替代方法。

 var str = "thisisasimpleinput"; var cpy = str; var indexes = []; var n = -1; for (var i = cpy.indexOf('i'); i > -1; i = cpy.indexOf('i')) { n += i; n++; indexes.push(n); cpy = cpy.slice(++i); } alert(indexes.toString()); 

var getLetterIndexes = function(word, letter) {
  var indexes = [];
  word.split("").forEach(function(el, i) {
    el === letter && indexes.push(i);
  });
  return indexes;
};

getLetterIndexes("tree", "e"); // [2, 3]

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

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