获取字符串中的字符索引

Get characters index in string

我想实现这样的目标:

如果数组 [ "a", "b", "c"] 包含 const word = "abracadabra" 的任何字符,请给我该字符及其在 const word 中的位置

我试过这样的方法:

const word = "abracadabra";
const input = ["a", "b", "c"];
for (let i = 0; i< word.length; i++) {
  if (input.includes(word(i))) {
  console.log(i + (word(i)));
  }
}

但这行不通,有人可以帮我解决逻辑和/或语法问题吗? 我是编码新手,感谢您的时间和精力!

访问数组的字段时必须使用方括号。括号用于调用函数。

const word = "abracadabra";
const input = ["a", "b", "c"];

for (let i = 0; i< word.length; i++) {
  if (input.includes(word[i])) {
      console.log(i + word[i]);
  }
}
for(let i=0;i<input.length;i++){
  if(word.indexOf(input[i]) != -1){
    console.log('word includes ',input[i])
  }
}

我想这会解决你的问题。

我认为发布问题(制定问题)足以让我想到更好的解决方案。我现在有一个工作片段:

const word = "abracadabra";
const inPut = ["a", "b", "c"];
for (let i = 0; i< word.length; i++) {
    for (let j = 0; j< (inPut.length); j++) {
        if (word.charAt(i).includes(inPut[j])) {
            console.log(i + (word.charAt(i)));

        }
    }
}

由于您的问题表述准确:

give me that character and its position in const word

使用RegExp.prototype.exec

const word = "abracadabra";
const input = ["a", "b", "c"];

input.forEach(c => {
  const re = new RegExp(c, "g");
  let m;
  while (m = re.exec(word)) console.log(`${c} found at index ${m.index}`);
});

另一种实现相同效果的好方法是使用 Array.prototype.reduce():

const word = "abracadabra";
const input = ["a", "b", "c"];

const res = input.reduce((ob, c) => {
  ob[c] = [...word].reduce((a, w, i) => {
    if (w === c) a.push(i);
    return a;
  }, []);
  return ob;
}, {});


console.log(res);

这将 return 一个对象,字符 属性 有一个包含所有位置出现的数组:

{
  "a": [0, 3, 5, 7, 10],
  "b": [1, 8],
  "c": [4]
}
const word = "abracadabra";
const input = ["a", "b", "c"];
for (let i = 0; i< word.length; i++) {
  if (input.includes(word[i])) {
  console.log(i + (word[i]));
  }
}

请使用方括号word[i]不要使用这个word(i)