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 分钟前
【小沐杂货铺】基于Three.JS构建IFC模型浏览器(WebGL、CAD、Revit、IFC)
javascript·webgl·three.js·bim·ifc·revit·ifc.js
程序猿小D1 分钟前
第4节 Node.js NPM 使用介绍
服务器·前端·vscode·npm·node.js
snakeshe101012 分钟前
9.update props
前端
snakeshe101014 分钟前
深入浅出:手把手实现Mini-React中的Props更新机制
前端
苍何15 分钟前
Office版的Cursor来了,MCP+PPT太酷啦!
前端·人工智能
RichardMiao19 分钟前
你真的清楚文件上传的进度展示吗,为啥进度显示不准确?
前端·全栈
每天都想着怎么摸鱼的前端菜鸟21 分钟前
uniapp开发app 实现简易的路由拦截器
vue.js·uni-app
驴肉板烧凤梨牛肉堡22 分钟前
babel+rollup打包pdfjs-dist的5.x.x高版本为es5产物,适应老项目
前端
随笔记22 分钟前
uniapp中获取设备wifi列表,已连接wifi信息
前端·javascript·uni-app
FairyDiana23 分钟前
【JavaScript】一篇文章,带你拿捏JS的预编译
javascript·面试