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:只是作遍历,不带返回值,但可以进行一些操作。

相关推荐
汝生淮南吾在北1 天前
SpringBoot+Vue饭店点餐管理系统
java·vue.js·spring boot·毕业设计·毕设
酒尘&1 天前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
学历真的很重要1 天前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)
前端·人工智能·vscode·后端·语言模型·负载均衡·ai编程
用户47949283569151 天前
"讲讲原型链" —— 面试官最爱问的 JavaScript 基础
前端·javascript·面试
用户47949283569151 天前
2025 年 TC39 都在忙什么?Import Bytes、Iterator Chunking 来了
前端·javascript·面试
JIngJaneIL1 天前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue心理健康管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
大怪v1 天前
【Virtual World 04】我们的目标,无限宇宙!!
前端·javascript·代码规范
狂炫冰美式1 天前
不谈技术,搞点文化 🧀 —— 从复活一句明代残诗破局产品迭代
前端·人工智能·后端
xw51 天前
npm几个实用命令
前端·npm