从一个数组创建一对数组,从而产生圆形数组 [英] Creating a pair of arrays from an array resulting in circular array

查看:67
本文介绍了从一个数组创建一对数组,从而产生圆形数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数接受一个数组并创建一对数组
,例如数组 [1,2,3,4] 该对将是:

I am trying to make a function that takes an array and creates a pair of arrays for example an array [1,2,3,4] the pair will be:

pair = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] ;

对将是:

pairs = [[[1,2],[1,3]], [[1,2],[1,4]], [[1,2],[2,3]] .... [[2,4],[3,4] ] ;

到目前为止,我的函数如下:

So far my function looks like this:

function makePairs(arr) {

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

  // i get the desired pair by the above nested for loop... 
  // console.log(pair) ; 

  // i try to do the same nested for loop with the pair array.. 
  // but i get [circular object Array]; 
  var k =  pair.length -1,
  pairs = [] ;
          for(var m=0; m < k ; m++ ) {
          for(var n=m+1; n <= k ; n++ ) {
            pairs.push( [pair[m],pair[n]]) ;
          }
        }
    return pairs; 
}

console.log(  makePairs([1,2,3,4]) );

所以给了我想要的对但是当我用 pair 数组对嵌套的
for 进行相同类型的循环时,得到的是 [圆形对象数组] 。我以为
嵌套的for循环也可以在上工作,但它不能。
我读到,循环引用是在javascript对象和本机对象之间形成的,导致内存泄漏,但我不知道这是否在这里发生。请帮忙。

So the pair gives me the desired pair but when I do the same type of nested for loop with the pair array, I get [circular object Array]. I thought the nested for loop will work on the pairs too but it does not. I read that circular reference is formed between a javascript object and a native object causing memory leak but I don't know if that's happening here. please help.

推荐答案

我想知道问题是否出在调试器本身上。每当引用已引用的项目时,它都会输出[圆形对象数组]。

I wonder if the issue is the debugger itself. It's outputting [circular object Array] any time it's referring to an item already referred to.

尝试制作更多控制台消息。将最后一行替换为:

Try making a lot more console messages. Replace your last line with:

var answer = makePairs([1,2,3,4]);
for (var i = 0; i < answer.length; ++i) {
    console.log("[[" + answer[i][0][0] + ", " + answer[i][0][1] + "], [" + 
         answer[i][1][0] + ", " + answer[i][1][1] + "]]");
}

我敢打赌它会打印出来。

I bet it will print out ok.

这篇关于从一个数组创建一对数组,从而产生圆形数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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