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。
相关推荐
2401_858286119 分钟前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
coder_pig24 分钟前
跟🤡杰哥一起学Flutter (三十四、玩转Flutter手势✋)
前端·flutter·harmonyos
万少30 分钟前
01-自然壁纸实战教程-免费开放啦
前端
独立开阀者_FwtCoder32 分钟前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
yuki_uix43 分钟前
AI辅助网页设计:从图片到代码的实践探索
前端
我想说一句43 分钟前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
陈随易43 分钟前
MoonBit助力前端开发,加密&性能两不误,斐波那契测试提高3-4倍
前端·后端·程序员
guygg881 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
汤姆Tom1 小时前
JavaScript reduce()函数详解
javascript
小飞悟1 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试