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

假设我想搜索 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);*/


aluckdog
浏览 91回答 4
4回答

holdtom

这将遍历 tickers 数组,如果它以“S”开头,则将其添加到 sCompanies 数组。tickers.forEach(function (item, index, array) {&nbsp; &nbsp; if (item.startsWith('S')) {&nbsp; &nbsp; &nbsp; &nbsp; sCompanies.push(item);&nbsp; &nbsp; }})

萧十郎

我还得到了以下代码作为模型解决方案,我理解使用这种格式的原因是因为我想针对首字母以外的其他内容:if(tickers[i][0]&nbsp;==&nbsp;'S')然后我可以使用 [1] 而不是 [0] 来定位第二个字母。

三国纷争

在你的循环中它会是这样的:for (i = 0; i < tickers.length; i++) {&nbsp; if (tickers[i].startsWith('S')) {&nbsp; &nbsp; sCompanies.push(tickers[i]);&nbsp; }}或者更现代一点for (const i in tickers) {&nbsp; if (tickers[i].startsWith('S')) {&nbsp; &nbsp; sCompanies.push(tickers[i]);&nbsp; }}更好的是使用for...ofwhich 来循环数组。for (const ticker of tickers) {&nbsp; if (ticker.startsWith('S')) {&nbsp; &nbsp; sCompanies.push(ticker);&nbsp; }}或者你可以像上面的答案一样做一个 oneliner。

Helenr

你为什么不像这样使用过滤器功能呢?// Only return companies starting by "S"const sCompanies = tickers.filter((companyName) => companyName.startsWith('S'))&nbsp;但是如果你想用 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++) {&nbsp; 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript