返回

给小朋友讲解JS数组操作,用emoji表情生动有趣

前端

小朋友们,今天我们来聊聊JS数组操作。数组是用来存储一组数据的,就像一个大盒子,里面可以放很多东西。

映射 (map)

映射就是把数组中的每一项都经过一个函数处理,然后得到一个新的数组。就像把数组中的每一只动物都变成一道菜。

const animals = ['🐶', '🐱', '🐭', '🐰'];
const foods = animals.map((animal) => {
  if (animal === '🐶') {
    return '🍖';
  } else if (animal === '🐱') {
    return '🐟';
  } else if (animal === '🐭') {
    return '🧀';
  } else if (animal === '🐰') {
    return '🥕';
  }
});

console.log(foods); // ['🍖', '🐟', '🧀', '🥕']

累加 (reduce)

累加就是把数组中的每一项都累加起来,得到一个最终结果。就像把所有的食材都累加起来,变成一道菜。

const ingredients = ['米饭', '蔬菜', '肉类'];
const dish = ingredients.reduce((prev, curr) => {
  return prev + curr;
});

console.log(dish); // '米饭蔬菜肉类'

过滤 (filter)

过滤就是把数组中的每一项都经过一个函数判断,然后把满足条件的项放到一个新的数组中。就像把所有的食材都过滤一遍,只留下可以吃的。

const foods = ['苹果', '香蕉', '梨', '西瓜', '菠萝'];
const edibleFoods = foods.filter((food) => {
  return food !== '菠萝';
});

console.log(edibleFoods); // ['苹果', '香蕉', '梨', '西瓜']

排序 (sort)

排序就是把数组中的每一项都按照一定的规则进行排序。就像把所有的食材都按照价格排序。

const prices = [10, 20, 30, 40, 50];
const sortedPrices = prices.sort((a, b) => {
  return a - b;
});

console.log(sortedPrices); // [10, 20, 30, 40, 50]

小朋友们,这就是JS数组操作的基本用法。希望你们能喜欢!