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

相关推荐
Rsun045516 小时前
React相关面试题
前端·react.js·前端框架
Lao乾妈官方认证唯一女友:D7 小时前
通过plasmo的wallet扩展添加新钱包
javascript·web3·区块链
ALKAOUA7 小时前
力扣面试150题刷题分享
javascript·笔记
鹏多多.7 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter·ios·前端框架
LawrenceLan7 小时前
37.Flutter 零基础入门(三十七):SnackBar 与提示信息 —— 页面反馈与用户交互必学
开发语言·前端·flutter·dart
迪巴拉15257 小时前
基于Vue与Spring Boot+Open Cv的智慧校园考勤系统
前端·vue.js·spring boot
swipe7 小时前
JavaScript 对象与属性描述符:从原理到实战
前端·javascript·面试
&活在当下&7 小时前
Vue3 h函数用法详解
前端·javascript·vue.js