vue3中查找字典列表中某个元素的值对应的列表索引值

vue3中查找字典列表中某个元素的值对应的列表索引值

目录

思路方法

要获取字典列表中某个元素的值对应的列表索引值,可以使用数组的 findIndex 方法。这个方法返回数组中满足提供的测试函数的第一个元素的索引。如果没有找到,则返回 -1。

代码实现示例

html 复制代码
<template>
  <div>
    <p>查找的结果: {{ foundObject }}</p>
    <p>索引值: {{ index }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'jack' },
        { id: 2, name: 'jason' },
        { id: 3, name: 'tom' }
      ],
      searchId: 2, // 我们想查找的对象的 id
      foundObject: null, // 存储查找到的对象
      index: -1 // 存储查找到的对象的索引值
    };
  },
  mounted() {
    this.findObjectAndIndexById();
  },
  methods: {
    findObjectAndIndexById() {
      // 首先使用 findIndex 方法查找索引值
      this.index = this.items.findIndex(item => item.id === this.searchId);
      
      // 如果找到了索引值,则使用索引值从数组中获取对象
      if (this.index !== -1) {
        this.foundObject = this.items[this.index];
      } else {
        // 如果没有找到,则重置 foundObject
        this.foundObject = null;
      }
    }
  }
};
</script>

解释说明

  • index 变量用于存储查找到的对象的索引值。
  • findObjectAndIndexById 方法首先使用 findIndex 方法查找 items 数组中满足 id 等于 searchId 的对象的索引值,并将其存储在 index 中。
  • 如果 index 不等于 -1(表示找到了对象),则使用 index 从 items 数组中获取对应的对象,并将其存储在 foundObject 中。
  • 如果 index 等于 -1(表示没有找到对象),则将 foundObject 重置为 null。
相关推荐
Thetimezipsby17 小时前
Redux、React Redux 快速学习上手、简单易懂、知识速查
前端·react.js·redux
微爱帮监所写信寄信17 小时前
微爱帮技术实践:阿里云短信接口的高可用优化方案
开发语言·网络协议·阿里云·云计算·php
后端小张17 小时前
【JAVA 进阶】Spring Boot自动配置详解
java·开发语言·人工智能·spring boot·后端·spring·spring cloud
郝学胜-神的一滴17 小时前
Python面向对象编程:解耦、多态与魔法艺术
java·开发语言·c++·python·设计模式·软件工程
有趣灵魂17 小时前
Java SpringBoot批量获取Minio中多个文件进行压缩成zip下载
java·开发语言·spring boot
黎明初时17 小时前
react基础框架搭建2-准备工作:react+router+redux+axios+Tailwind+webpack
前端·react.js·webpack
csbysj202017 小时前
CSS3 圆角
开发语言
消失的旧时光-194317 小时前
从 Kotlin 到 Flutter:架构迁移指南
开发语言·flutter·kotlin
phil zhang17 小时前
Celer:为大型C/C++项目打造的极简包管理器
开发语言·c++·elasticsearch
threerocks17 小时前
我的年终总结 - 艰难的 2025
前端·面试·年终总结