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。
相关推荐
草莓熊Lotso7 分钟前
《算法闯关指南:优选算法--二分查找》--19.x的平方根,20.搜索插入位置
java·开发语言·c++·算法
旭意10 分钟前
C++蓝桥杯之函数与递归
开发语言·c++·蓝桥杯
。TAT。10 分钟前
C++ - vector
开发语言·c++·学习
杨福瑞11 分钟前
C语言数据结构:算法复杂度(1)
c语言·开发语言·数据结构
携欢13 分钟前
PortSwigger靶场之Exploiting server-side parameter pollution in a REST URL通关秘籍
前端·javascript·安全
郭源潮122 分钟前
《Muduo网络库:实现one loop per thread设计模式》
开发语言·c++·网络库
鹏多多25 分钟前
今天你就是VS Code之神!15个隐藏技巧让代码效率翻倍
前端·程序员·visual studio code
linksinke34 分钟前
html案例:制作一个图片水印生成器,防止复印件被滥用
开发语言·前端·程序人生·html
寒月霜华34 分钟前
JavaWeb-html、css-网页正文制作
前端·css·html
执沐38 分钟前
HTML实现流星雨
前端·html