如何迭代对象中所有唯一的条目对? [英] How can I iterate over all unique pairs of entries in an object?

查看:121
本文介绍了如何迭代对象中所有唯一的条目对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个数组数据结构,我这样迭代,在每个独特的元素对上调用 foo

I currently have an array data structure that I iterate over like this, calling foo on each unique pair of elements.

for(var i = 0; i < arr.length; i++) {
    for(var j = i + 1; j < arr.length; j++) {
        foo(arr[i], arr[j]);
    }
}

然而,我意识到我宁愿使用对象而不是数组,因为我可以很容易地按名称添加和删除元素。

However, I've realized that I'd rather use an object instead of an array, since I can then add and remove elements by name very easily.

但是,我看不到一种明显的方法来迭代这样的一个东西。我能得到的最接近的是:

However, I can't see an obvious way to iterate over such an object. The closest I can get is:

for(i in obj) {
    for(j in obj) {
        foo(obj[i], obj[j]);
    }
}

显然,这将是每对两次,甚至产生一对相同的元素。是否有一种简单的方法来迭代对象的方式与我在第一个代码示例中的数组相同?

Obviously, this will do each pair twice, and even produce a pair of identical elements. Is there an easy way to iterate over an object in the same way as I do in the array in my first code sample?

jsperf 上测试解决方案的性能。

Performance testing the solutions on jsperf.

推荐答案

我的解决方案最初是作为评论写的:

My solution that was at first written as a comment:

添加 if(i< j)内循环中的条件。它可能不是最好的解决方案,但只要foo函数为 foo(2,10) foo做同样的事情它就会起作用。 (10,2)

Add an if (i < j) condition in the inner loop. It might not be the best solution, but it would work as long as the foo function does the same thing for foo(2, 10) and foo(10, 2):

for(i in obj) {
    for(j in obj) {
        if (i < j) {
            foo(obj[i], obj[j]);
        }
    }
}

这篇关于如何迭代对象中所有唯一的条目对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆