【问题标题】:Get characters index in string获取字符串中的字符索引
【发布时间】:2021-07-19 05:55:24
【问题描述】:

我想实现这样的目标:

如果数组 [ "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)));
  }
}

但这不起作用,有人可以帮助我了解逻辑和/或语法吗? 我是编码新手,感谢您的时间和精力!

【问题讨论】:

  • 你知道word(i)word[i]的区别吗?
  • “不起作用”不是计算机所说的。它说“单词不是函数”,这清楚地表明问题出在哪里 - 您正在尝试使用不是函数的东西作为函数。
  • 感谢您的提示!

标签: javascript arrays string include


【解决方案1】:

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

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]);
  }
}

【讨论】:

  • 如果此答案解决了您的问题,请将其标记为解决方案。
【解决方案2】:

由于您的问题已准确说明:

给我那个字符和它在 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);

这将返回一个对象,其中字符属性具有一个包含所有位置出现的数组:

{
  "a": [0, 3, 5, 7, 10],
  "b": [1, 8],
  "c": [4]
}

【讨论】:

    【解决方案3】:
    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)

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 一个更详细的版本,您所要做的就是索引字符串而不是尝试调用它,即将word(i)替换为word[i]?
      【解决方案5】:
      for(let i=0;i<input.length;i++){
        if(word.indexOf(input[i]) != -1){
          console.log('word includes ',input[i])
        }
      }
      

      我认为这将解决您的问题。

      【讨论】:

      • 您知道这段代码不正确吗?结果与描述完全不符。
      猜你喜欢
      • 2012-06-29
      • 1970-01-01
      • 2019-07-22
      • 2014-12-02
      • 2023-03-11
      • 2011-11-21
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多