【前端学习笔记】todos.value.filter((t) => t !== todo)

todos.value.filter((t) => t !== todo)

(t) => t !== todo实际上就是

function(t){
        return t !==todo
}
  • t是一个形参,不用考虑他的具体意义,它可以是a,也可以是b…
  • 这段代码是JavaScript中的数组方法filter()的应用。它的作用是从数组this.todos中筛选出所有不等于传入参数todo的元素,并返回一个新的数组。具体来说,箭头函数(t) => t !== todo表示对于数组中的每一个元素t,只有当t不等于传入的参数todo时,才将其保留在新数组中。这个方法不会改变原数组,而是返回一个新的数组。
// 举例说明
let arr = [1, 2, 3, 4, 5];
let arr_new 
let remove = 3;
arr_new = arr.filter((item) => item !== remove);
console.log(arr); // 输出 [1, 2, 3, 4, 5]
console.log(arr_new); // 输出 [1, 2, 4, 5]

let arr2 = [1, 2, 3, 4, 5];
let remove2 = [1, 2, 3];
arr2 = arr2.filter((item) => !remove2.includes(item));
console.log(arr2); // 输出:[4,5]

JavaScript 数组filter方法完整介绍:http://t.csdn.cn/9Ho6q
做vue官方教程看见的,作为初学者一脸懵:https://cn.vuejs.org/tutorial/#step-7

<script setup>
import { ref } from 'vue'

// 给每个 todo 对象一个唯一的 id
let id = 0

const newTodo = ref('')
const todos = ref([
  { id: id++, text: 'Learn HTML' },
  { id: id++, text: 'Learn JavaScript' },
  { id: id++, text: 'Learn Vue' }
])

function addTodo() {
  todos.value.push({ id: id++, text: newTodo.value })
  newTodo.value = ''
}

function removeTodo(todo) {
  todos.value = todos.value.filter((t) => t !== todo)
}
</script>

<template>
  <form @submit.prevent="addTodo">
    <input v-model="newTodo">
    <button>Add Todo</button>    
  </form>
  <ul>
    <li v-for="todo in todos" :key="todo.id">
      {{ todo.text }}
      <button @click="removeTodo(todo)">X</button>
    </li>
  </ul>
</template>
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值