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。
相关推荐
小高00716 小时前
2026 年,只会写 div 和 css 的前端将彻底失业
前端·javascript·vue.js
Anita_Sun16 小时前
Lodash 源码解读与原理分析 - Lodash 原型链的完整结构
前端
梁森的掘金16 小时前
Frida Hook 流程
前端
知秋正在99616 小时前
Java实现Html保存为.mhtml文件
java·开发语言·html
www_stdio16 小时前
Git 提交AI神器:用大模型帮你写出规范的 Commit Message
前端·javascript·react.js
陈随易16 小时前
Bun v1.3.6发布,内置tar解压缩,各方面提速又提速
前端·后端
双向3316 小时前
【AIGC爆款内容生成全攻略:如何用AI颠覆内容创作效率?】
前端
摘星编程16 小时前
Flutter for OpenHarmony 实战:SliverList 滑动列表详解
android·javascript·flutter
陈_杨16 小时前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP-- 卡片编辑功能
前端·harmonyos
q***441516 小时前
Java性能优化实战技术文章大纲Java性能优化的核心目标与原则
java·开发语言·性能优化