为了账号安全,请及时绑定邮箱和手机立即绑定

如何按元素首字母过滤 JavaScript 数组?

如何按元素首字母过滤 JavaScript 数组?

aluckdog 2022-12-18 16:34:23
假设我想搜索 tickers 数组并返回数组中以 S 开头的所有项目,然后将它们写入 sCompanies = []。任何人都知道我如何使用 for 或 while 循环来解决这个问题?// Iterate through this list of tickers to build your new array:let tickers = ['A', 'SAS', 'SADS' 'ZUMZ'];//console.log(tickers);// Define your empty sCompanies array here://Maybe need to use const sComapnies = [] ?let sCompanies = []// Write your loop here:for (i = 0; i < tickers.length; i++) {  console.log(tickers[i]);  }// Define sLength here:sLength = 'test';/*// These lines will log your new array and its length to the console:console.log(sCompanies);console.log(sLength);*/
查看完整描述

4 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

这将遍历 tickers 数组,如果它以“S”开头,则将其添加到 sCompanies 数组。


tickers.forEach(function (item, index, array) {

    if (item.startsWith('S')) {

        sCompanies.push(item);

    }

})


查看完整回答
反对 回复 2022-12-18
?
萧十郎

TA贡献1815条经验 获得超12个赞

我还得到了以下代码作为模型解决方案,我理解使用这种格式的原因是因为我想针对首字母以外的其他内容:

if(tickers[i][0] == 'S')

然后我可以使用 [1] 而不是 [0] 来定位第二个字母。


查看完整回答
反对 回复 2022-12-18
?
三国纷争

TA贡献1804条经验 获得超7个赞

在你的循环中它会是这样的:


for (i = 0; i < tickers.length; i++) {

  if (tickers[i].startsWith('S')) {

    sCompanies.push(tickers[i]);

  }

}

或者更现代一点


for (const i in tickers) {

  if (tickers[i].startsWith('S')) {

    sCompanies.push(tickers[i]);

  }

}

更好的是使用for...ofwhich 来循环数组。


for (const ticker of tickers) {

  if (ticker.startsWith('S')) {

    sCompanies.push(ticker);

  }

}

或者你可以像上面的答案一样做一个 oneliner。


查看完整回答
反对 回复 2022-12-18
?
Helenr

TA贡献1780条经验 获得超3个赞

你为什么不像这样使用过滤器功能呢?


// Only return companies starting by "S"

const sCompanies = tickers.filter((companyName) => companyName.startsWith('S')) 

但是如果你想用 for 循环来做,你可以检查一下:


// Iterate through this list of tickers to build your new array:

const tickers = ["A", "SAS", "SADS", "ZUMZ"];


//console.log(tickers);


// Define your empty sCompanies array here:

const sCompanies = [];


// Write your loop here:

for (let i = 0; i < tickers.length; i++) {

  tickers[i].startsWith("S") && sCompanies.push(tickers[i]);

}


// Define sLength here:

const sLength = sCompanies.length;


/*

// These lines will log your new array and its length to the console:

*/

console.log(sCompanies);

console.log(sLength);


查看完整回答
反对 回复 2022-12-18
  • 4 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信