简体   繁体   English

奇怪的jQuery多类型锯齿状数组

[英]jquery multitype Jagged array behaving strangely

Please refer to this: 请参考此:

http://jsfiddle.net/MasterOfKitties/v7xbu/7/ http://jsfiddle.net/MasterOfKitties/v7xbu/7/

/*This is the desired behavior*/
/*var A = [1, 2, 3]*/
/*var B = "hello", [1, 2, 3],
         "hello", [2, 3, 2],
         "hello", [1, 5, 1]]*/

var A = new Array();
var B = new Array();

function fnMakeArray()
    {
     var strTemp;
     var arrTemp = new Array();
     strTemp = parseInt(window.prompt("Enter a number until you hit cancel",""));  


  while (strTemp>0)
      {
         arrTemp.push(strTemp);   
         strTemp =  parseInt(window.prompt("Enter a number until you hit cancel",""));
      }  
        A[0] = "hello";
        A[1] = arrTemp;
        alert(A);
    }


function fnReplicateArray()
    {
        B.push(A); 
        fnDisBArray();
        alert(B);

    }

function fnDisBArray()
{
    var strTemp;
 for(var x = 0; x<B.length;x++)
     {
         strTemp += "<P>" + B[x] + "</p>"

     }
     document.getElementById('parse').innerHTML = strTemp ;  


}

For some reason, when attempting to display the B array, it puts out undefined. 由于某些原因,当试图显示B数组时,它输出的是undefined。 Furthermore, it does not seem to increment the jagged array correctly, as the b[0] element begins to radically change even though the b[1] or b[2] element is being arranged. 此外,即使b [1]或b [2]元素被排列,b [0]元素也开始发生根本变化,似乎并不能正确地增加锯齿状数组。

Any assistance? 有什么帮助吗? What's going on? 这是怎么回事?

you have to initialize strTemp with a value. 您必须使用值初始化strTemp

like 喜欢

var strTemp = "";

instead of 代替

var strTemp;

in your case. 在你的情况下。

when the line 当行

 strTemp += "<P>" + B[x] + "</p>"

is executing for the first time strTemp is undefined so its converted to string as undefined and gets appended in the begining 在第一次执行strTemp undefined因此将其转换为undefined并被附加到开头

see the working fiddle 看到工作的小提琴

Your function does not "replicate"/copy the A array, it just pushes a reference to A into B. I believe you want: 您的函数不会“复制” /复制A数组,它只是将对A的引用推入B。我相信您想要:

B = A.slice(0); 

Now, you seem to have another problem: if you enter eg 10 and 11 into the prompts, you get this array at the end: 现在,您似乎还遇到了另一个问题:如果在提示中输入例如10和11,则会在末尾得到以下数组:

[
    "hello",
    [
        10,
        11
    ]
]

I suspect that's not really what you're looking for. 我怀疑这不是您真正想要的。 Could you please explain what you're really trying to accomplish? 您能解释一下您真正要完成的工作吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM