js遍历集合
包括使用数组的filter方法、map方法,或者通过简单的循环。下面是一些常见的方法:
filter
const items = [
{ id: 1, name: 'Apple', type: 'fruit' },
{ id: 2, name: 'Carrot', type: 'vegetable' },
{ id: 3, name: 'Banana', type: 'fruit' },
{ id: 4, name: 'Potato', type: 'vegetable' }
];
// 过滤出所有水果
const fruits = items.filter(item => item.type === 'fruit');
console.log(fruits);
map
const fruits = items.map(item => {
if (item.type === 'fruit') {
return item; // 只返回符合条件的对象
}
});
// 需要过滤掉undefined或null值
const filteredFruits = fruits.filter(Boolean);
console.log(filteredFruits);
const arr = ["apple", "banana", "orange", "grape"];
arr.sort(); // ["apple", "banana", "grape", "orange"]
js- filter过滤数组
最新推荐文章于 2025-12-18 10:02:55 发布
1297

被折叠的 条评论
为什么被折叠?



