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

相关推荐
招来红月2 小时前
记录JS 实用API
javascript
别叫我->学废了->lol在线等2 小时前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
霍夫曼2 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn08952 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
DARLING Zero two♡3 小时前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper
꒰ঌ小武໒꒱3 小时前
文件上传全维度知识体系:从基础原理到高级优化
javascript·node.js
Lovely Ruby3 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
老华带你飞3 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JIngJaneIL3 小时前
基于Java酒店预约系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
深红3 小时前
玩转小程序AR-实战篇
前端·微信小程序·webvr