likes
comments
collection
share

数组对象判重最佳实践

作者站长头像
站长
· 阅读数 26

数组对象判重最佳实践

数组对象判重最佳实践 赶紧挣钱,回家过年......

1.问题回顾

       deviceSelectedRow(row) {
        this.ElectricalPartList.push(row)
      },

在此方法中,ElectricalPartList需要多次push进去数据,但是row可能存在重复,如何判重呢?

我要求根据partId判重,重复就不再push进去

2.问题解决

根据代码片段,想要在 ElectricalPartList 数组中添加新的元素 row,但是如果该元素的 partId 已经存在于数组中,就不再添加。可以使用一些数组方法来实现这一目标,例如 some 方法来检查数组中是否存在相同的 partId。下面是一个可能的实现:

deviceSelectedRow(row) {
  // 检查是否存在相同的 partId
  const isDuplicate = this.ElectricalPartList.some(item => item.partId === row.partId);

  // 如果不存在重复的 partId,则将 row 添加到 ElectricalPartList 中
  if (!isDuplicate) {
    this.ElectricalPartList.push(row);
  }
}

在这个代码中,some 方法用于检查数组中是否存在满足指定条件的元素。如果存在具有相同 partId 的元素,则 isDuplicate 将为 true,否则为 false。根据这个条件,我们决定是否将新的 row 添加到 ElectricalPartList 数组中。

3.问题拓展

Array.prototype.some() 方法用于检测数组中是否至少有一个元素满足指定条件。这个方法会遍历数组,对每个元素应用提供的测试函数,直到找到一个使测试函数返回 true 的元素。如果找到这样的元素,some 方法将立即返回 true,否则返回 false

下面是对 some 方法的详细解释以及一些用法示例:

some 方法的语法:

array.some(callback(element, index, array), thisArg);
  • callback 是一个用来测试数组元素的函数,它接受三个参数:

    • element: 当前被处理的元素。
    • index (可选): 当前处理元素的索引。
    • array (可选): 调用 some 的数组。
  • thisArg (可选): 执行回调函数时,用作 this 的对象。

示例 1: 检测数组中是否存在偶数

const numbers = [1, 3, 5, 7, 8, 9];

const hasEven = numbers.some(function(element) {
  return element % 2 === 0;
});

console.log(hasEven); // 输出 true

示例 2: 使用箭头函数进行同样的检测

const numbers = [1, 3, 5, 7, 9];

const hasEven = numbers.some(element => element % 2 === 0);

console.log(hasEven); // 输出 false

示例 3: 检测数组中是否有字符串长度大于等于 5 的元素

const words = ["apple", "banana", "kiwi", "orange"];

const hasLongString = words.some(word => word.length >= 5);

console.log(hasLongString); // 输出 true

示例 4: 使用 thisArg 指定回调函数中的 this

const contextObject = { threshold: 10 };

const numbers = [2, 5, 8, 12];

const hasValueAboveThreshold = numbers.some(function(element) {
  return element > this.threshold;
}, contextObject);

console.log(hasValueAboveThreshold); // 输出 true

这些示例演示了 some 方法的基本用法,可以根据具体的需求调整回调函数来进行不同的测试。