本文介绍了如何获取所有成对的数组JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用所有可用的数组元素对来调用函数.像这样:
I need to call function with all avaliable pairs of array elements. Like this:
[1, 2, 3].pairs(function (pair) {
console.log(pair); //[1,2], [1,3], [2,3]
});
推荐答案
您应该尝试向我们展示自己已经解决了问题,而不仅仅是要求我们提供答案,但这是一个有趣的问题,因此,这里:
You should try to show us that you've solved the problem yourself instead of just asking us for the answer, but it was an interesting problem, so here:
Array.prototype.pairs = function (func) {
for (var i = 0; i < this.length - 1; i++) {
for (var j = i; j < this.length - 1; j++) {
func([this[i], this[j+1]]);
}
}
}
var list = [1, 2, 3];
list.pairs(function(pair){
console.log(pair); // [1,2], [1,3], [2,3]
});
这篇关于如何获取所有成对的数组JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!