我正在嘗試按特定的名字過濾一組全名。我創建了一個filterFirstName函式,它接受名稱引數和與之比較的標準。
然后我在我的過濾器中使用該功能。我查找了 filter 的語法callback(element[, index[, array]]。元素是 thefullName但 thenameQuery不是 theindex或array。
我將fullNames陣列和"John"字串作為引數傳遞,以防它知道"John"用作nameQuery變數。那也收到了一個錯誤。
我找不到任何說明這種情況的指導,因此我可能需要被引導到不同的方法。
//loop to get random names with one person named "John Smith"
var fullNames = (getNames = () => {
let names = [];
for (let i = 0; i < 9; i ) {
names.push(`Human${i} Person${i}`);
}
names.push("John Smith");
return names;
})();
var filterFirstName = (fullName, nameQuery) =>
fullName.split(" ")[0] === nameQuery;
var searchFirstNames = (namesAr, nameQuery) =>
namesAr.filter(filterFirstName)(fullNames, "John");
uj5u.com熱心網友回復:
您可以將這兩個功能簡化為一個。
//loop to get random names with one person named "John Smith"
var fullNames = (getNames = () => {
let names = [];
for (let i = 0; i < 9; i ) {
names.push(`Human${i} Person${i}`);
}
names.push("John Smith");
return names;
})();
var searchFirstNames = (namesAr, nameQuery) => namesAr.filter(person => person.split(" ")[0] === nameQuery)
searchFirstNames(fullNames, "John")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537347.html
下一篇:PHP按“深度”合并陣列?
