检查是否没有数组元素满足条件。

huangapple go评论50阅读模式
英文:

Check if no array elements fulfill a condition

问题

以下是已翻译的内容:

我需要在 JavaScript 代码中执行一个动作,只有当数组中没有元素满足条件时才执行。最优的方法是什么?

在这种特定情况下,我只需要在数据层中推送某些东西,前提是它还没有存在。这是我所做的:

if (!window.dataLayer.some(
     (element) => element.event === 'some_label',
   )) {
    gtm.push(someTrackingObject);
   }

是否有更好/更简洁的方法?

英文:

I need to perform an action in JavaScript code only if no array elements fulfill a condition. What's the optimal way to do it?

In this particular case, I need to push something to the dataLayer only if it's not already present. Here's what I did:

if (!window.dataLayer.some(
     (element) => element.event === 'some_label',
   )) {
    gtm.push(someTrackingObject);
   }

Is there a better / more concise way?

答案1

得分: 1

你可以使用 .every()

如果你想检查是否没有元素满足特定条件,只需反转条件:

datalayer.every((element) => element.event !== "some_label")

> true // 如果没有元素具有 "some_label"
> false // 如果某些元素具有 "some_label"

使用 .some() 就足够了,所以 .every() 只是一种替代方式。

英文:

You can use .every()

If you want to check if no elements fulfull one specific condition, just inverse the condition

datalayer.every((element) => element.event !== "some_label")

> true // if no elements has "some_label"
> false // if some element has "some_label"

Using .some() is good enough, so .every() is just an alternative way.

答案2

得分: 1

你当前使用的Array.prototype.some()方法来检查数组元素是否满足条件是最优的,因为它在条件满足时立即停止对数组的迭代,避免了不必要的迭代。

如果你想要更简洁的版本,你可以使用Array.prototype.indexOf()方法来实现相同的结果:

if (window.dataLayer.indexOf(someTrackingObject) === -1) {
    gtm.push(someTrackingObject);
}

在这里,Array.prototype.indexOf()返回给定元素在数组中第一次出现的索引,如果不存在则返回-1。请注意,这种方法假定someTrackingObject在window.dataLayer数组中是唯一的。

这两种方法都有各自的优缺点:

  • Array.prototype.some():

    • 优点:
      • 在数组中的元素早期找到时,立即停止对数组的迭代,使得在元素早期找到的情况下更加高效。
    • 缺点:
      • 比Array.prototype.indexOf()不够简洁。
  • Array.prototype.indexOf():

    • 优点:
      • 比Array.prototype.some()更加简洁。
    • 缺点:
      • 不会在找到元素后停止对数组的迭代,如果元素在数组末尾找到的话可能效率较低。

总之,你当前使用的Array.prototype.some()方法是最适合检查是否有数组元素满足条件的方法,如果someTrackingObject在window.dataLayer数组中是唯一的,你可以考虑使用Array.prototype.indexOf()来获得更简洁的版本。

英文:

Your current approach using Array.prototype.some() is optimal for checking if no array elements fulfill a condition, as it stops iterating over the array as soon as the condition is met, avoiding unnecessary iterations.

if (!window.dataLayer.some((element) => element.event === 'some_label')) {
    gtm.push(someTrackingObject);
}

However, if you want a more concise version, you can use the Array.prototype.indexOf() method to achieve the same result:

if (window.dataLayer.indexOf(someTrackingObject) === -1) {
    gtm.push(someTrackingObject);
}

Here, Array.prototype.indexOf() returns the first index at which a given element can be found in the array, or -1 if it is not present. Note that this approach assumes that someTrackingObject is unique in the window.dataLayer array.

Both approaches have their pros and cons:

  • Array.prototype.some():
    • Pros:
      • Stops iterating over the array as soon as the condition is met, making it more efficient in cases where the element is found early in the array.
    • Cons:
      • Less concise than Array.prototype.indexOf()
  • Array.prototype.indexOf():
    • Pros:
      • More concise than Array.prototype.some().
    • Cons:
      • Does not stop iterating over the array, which may be less efficient if the element is found late in the array.

In summary, your current approach using Array.prototype.some() is optimal for checking if no array elements fulfill a condition, and you can consider using Array.prototype.indexOf() for a more concise version if someTrackingObject is unique in the window.dataLayer array.

答案3

得分: 1

你已经做的方法是一个不错的方式。你也可以使用 .every() 并检查是否不等于 !== 'some_label'

如果你有大量的数据,你可以使用 map 或 set 来提高查找的效率。但这只在你有多次查找和大型数组大小时才有意义。

// 使用 set 构建集合并添加事件
const set = window.dataLayer.reduce((acc, el) => {
    acc.add(el.event);
    return acc;
}, new Set())

// 检查集合是否包含标签
if (!set.includes('some_label')) {
    gtm.push(someTrackingObject);
}

更新

搜索元素。.find 在第一次匹配时退出,因此你不必检查数组中的每个元素。

// 检查集合是否包含标签
if (window.dataLayer.find(el => el.event === 'some_label') === undefined) {
    gtm.push(someTrackingObject);
}
英文:

What you did already is a good way to do it. You can also use .every() and check for !== 'some_label'.

If you have a lot of data you can use a map or set to be more efficient when it comes to lookup time. But this only makes sense when you have multiple lookups and a large array size.

// build set with set and events
const set = window.dataLayer.reduce((acc, el) => {
    acc.add(el.event);
    return acc;
}, new Set())


// check if the set includes the label
if (!set.includes('some_label')) {
    gtm.push(someTrackingObject);
}

Update

Search for the element. .find exits on the first match so you don't have to check every element in the array.

// check if the set includes the label
if (window.dataLayer.find(el => el.event === 'some_label') === undefined) {
    gtm.push(someTrackingObject);
}

huangapple
  • 本文由 发表于 2023年5月25日 15:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定