【问题标题】:Create an array from the output of a function inside a for loop [duplicate]从for循环内的函数输出创建一个数组[重复]
【发布时间】:2021-05-26 03:27:45
【问题描述】:

我想通过使用 for 循环函数来获取数组 split_Sentence 中所有出现的 "they""some" 的位置。然后我想从 for 循环函数的输出构建一个数组。但问题是,每当我使用indexOf() 查找位置时,它总是给出第一次出现的位置。我不知道如何从 for 循环的输出中创建一个数组。
谁能帮助我,我将不胜感激。

var Sentence = "some warriors know when they are defeated, whether some of them are too stubborn to accept it and they are the one who die. "
var split_Sentence = Sentence.split(" ")
/* function() ==> then sort an array listing all its output*/
Expected outcome: final array should be like this array= (0,4,8,18) 

如果你不明白我的问题,请尽管问我

【问题讨论】:

标签: javascript html arrays sorting


【解决方案1】:

注意:根据需要处理大写小写。

const Sentence = "some warriors know when they are defeated, whether some of them are too stubborn to accept it and they are the one who die.";
const arrayOfIndex = Sentence
  .split(" ")
  .map((word, index) => word === "some" || word === "they" ? index : false)
  .filter(x => x !== false);
console.log({arrayOfIndex});

【讨论】:

  • 如何访问控制台日志?以备将来使用?
  • 没有得到问题,如果你的意思是如何访问这些索引它只是一个数组,所以你可以访问arrayOfIndex
  • @SouradipMandal F12 和 ctrl+shift+j(取决于操作系统/浏览器)
猜你喜欢
  • 2023-04-01
  • 2019-08-28
  • 2012-09-21
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 2012-09-11
相关资源
最近更新 更多