TS中forEach与map,filter的简单事例及简单的说明

1、先上一张效果图:

2、再上一个代码:

复制代码
<template>
  <div>
    <h1>Array Test</h1>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
    <div style="display: flex; flex-direction: column; height: 200px; justify-content: space-between;">
      <button @click="items.push({ id: 4, name: `Item ${items.length + 1}` })">
        Add Item
      </button>
      <button @click="filterTest">filter return</button>
      <button @click="forEachTest">forEach</button>
      <button @click="mapTest">Map return</button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";

const items = ref([
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" },
]);

function filterTest() {
  const filtered = items.value.filter((item) => item.id > 2);
  console.log(filtered);
}

function forEachTest() {
  items.value.forEach((item) => {
    console.log(item.name);
  });
}

function mapTest() {
  const mapped = items.value.map((item) => {
    return {
      ...item,
      name: item.name.toUpperCase(),
    };
  });
  console.log(mapped);
}
</script>
<style scoped></style>

3、说明:

filter:根据条件来过滤,并且返回一个过滤以后的数组。

map:遍历数组,并处理数据 ,返回一个处理后的数组。

forEach:只是作遍历,不带返回值,但可以进行一些操作。

相关推荐
IT_陈寒1 分钟前
React子组件莫名其妙重渲染?你可能漏了这个Hook
前端·人工智能·后端
乘风gg12 分钟前
DeepSeek V4.1 Flash 来了,明天中午 Flash 降价 60%
前端·ai编程·claude
默_笙34 分钟前
❗ 给金鱼装记忆(上):从白板到笔记本,AI 的短期记忆生存指南
前端·javascript
酷酷的逗逗乐35 分钟前
前端转 Agent 开发 · 第五节:Memory 会话记忆
前端·程序员
掘金挖土1 小时前
前端手摸手跑路之 AI 应用开发(二)
前端·后端
兜里只有三分钱~1 小时前
翻卡_3D 的仪式感,和三个让它穿帮的写法
javascript·css·3d
mayaairi1 小时前
Vue2 组件通讯(四):v-model、scoped样式、mixins与plugins
前端·javascript·vue.js
梦曦i2 小时前
@meng-xi/uni-router 未来展望:夯实基础、深化体验、探索前沿
前端·uni-app
前端炒粉2 小时前
DOM 常用 API 速查表
开发语言·javascript·ecmascript
Yeyu2 小时前
AAOS AppCard 实践:怎么把自己的 App 塞进别人的卡片里
前端