0

请参考这个:

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 ;  


}

出于某种原因,当尝试显示 B 数组时,它会显示未定义。此外,它似乎没有正确地增加锯齿状数组,因为即使 b[1] 或 b[2] 元素正在排列,b[0] 元素也开始发生根本变化。

有什么帮助吗?这是怎么回事?

4

2 回答 2

2

你必须strTemp用一个值初始化。

喜欢

var strTemp = "";

代替

var strTemp;

在你的情况下。

当线

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

是第一次执行,strTemp所以undefined 它转换为字符串 asundefined并在开头附加

看到工作小提琴

于 2013-09-27T18:24:28.850 回答
1

Your function does not "replicate"/copy the A array, it just pushes a reference to A into B. I believe you want:

B = A.slice(0); 

Now, you seem to have another problem: if you enter e.g. 10 and 11 into the prompts, you get this array at the end:

[
    "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?

于 2013-09-27T18:23:09.187 回答