我有一個陣列,其中包含包含各種鍵和值的物件。我將從陣列中挑選出某些值,并檢查陣列中是否包含特定值。
function groupByName (contract) {
const { age } = contract;
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
...
];
...
}
為了比較ageingroups陣列,現在我必須使用回圈函式,然后一個一個地檢查。喜歡
groups.forEach(g => {
if (g.age === age) {
...
} else {
...
}
});
但我不喜歡這種方法,認為有簡單有效的方法。請幫我!
uj5u.com熱心網友回復:
你可以filter用來創建兩個子串列
像這樣
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
]
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)
const age30 = withAge(30)
const ageNot30 = withoutAge(30)
age30.forEach(g => {
console.log('do some stuff with age 30', g)
})
ageNot30.forEach(g => {
console.log('do some stuff without age 30', g)
})
uj5u.com熱心網友回復:
也許你可以看到這個功能
groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false
或閱讀此https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
順便說一下,如果你想在回圈中執行 if/else 片段,也許你應該使用 forEach
uj5u.com熱心網友回復:
您可以使用.find()方法來獲得確切的結果
groups.find( group => group.age === age);
這是一個完整的代碼
function groupByName(contract) {
const { age } = contract;
const groups = [
{ name: 'John', age: 30 },
{ name: 'Jack', age: 33 },
{ name: 'Tom', age: 40 },
];
return groups.find((group) => group.age === age); // Returns the result
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/535708.html
標籤:javascript
