繁体   English   中英

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

[英]How can I filter a JavaScript array by element first letter?

假设我想搜索 tickers 数组并返回数组中以 S 开头的所有项目,然后将它们写入 sCompanies = []。

任何人都知道我 go 如何使用 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);*/

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

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

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

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...of循环 arrays。

for (const ticker of tickers) {
  if (ticker.startsWith('S')) {
    sCompanies.push(ticker);
  }
}

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

这将 go 通过代码数组,如果它以“S”开头,则将其添加到 sCompanies 数组。

tickers.forEach(function (item, index, array) {
    if (item.startsWith('S')) {
        sCompanies.push(item);
    }
})

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM