2015-12-24 138 views
0

遇到一些麻煩與下面的代碼段:未定義陣列/ JavaScript的

I would like to be able to view the contents of $prisonlist in the console

我想能夠在控制檯查看的$prisonlist(或$prisonlist[some value])中的內容,並將其顯示在div的文本中。 從本質上講,每當我這樣做,它想出了被稱爲「未定義」的錯誤 - 儘管我與它的工作等功能似乎只是正常工作(如//

代碼:

 $counter = 0; 
       var $prisonlist=[]; 
       $prisonlist[0]=1; 
       $('#entered').text($prisonlist[0]); 
       $('#s1').click(function(){ 
        $(this).toggleClass('on off'); 
        $counter = $counter + 1; 
        $('#clicks').text($counter); 
        $prisn = Math.ceil(Math.random()*10); 
        $('#prisoners').text($prisn); 
        $boo=$prisonlist.indexOf($prisn) //finds in array whether there is any 

        if ($boo==-1){ 
        $prisonlist.push($prisn); // lists the individual inside 
         } 

       }); 
+0

你是否試圖訪問其範圍內的'$ prisonlist'? – Hatchet

+0

我猜這是你的意思超出了它的最大數組長度 - 不,如果我嘗試訪問在那裏定義的'$ prisonlist [0]',它不會顯示任何東西。它會顯示在文本中,如果我改變文本,但我不能查看完整的數組,當各種值已被推入它。 – squeakcode

+0

我認爲@hatchet實際上是在詢問'var $ prisonlist'的定義範圍。它是一個函數的本地函數,它是一個循環還是它在全局範圍內? –

回答

2

聲明var $prisonlist=[];的作用範圍,因此在控制檯中,你可以看到全球唯一的東西不可用的解決方案是:

  • 快速又醜 - 申報$prisonlist=[];(不var)在日全球範圍。

  • 我的首選 - 無論你想檢查變量插入console.log($prisonlist)。這會將變量的當前值記錄到控制檯。

  • 使用調試器

+0

非常感謝!這工作完美。 – squeakcode

+0

太棒了!所以請接受答案 – avnr

+0

我只做了它,因爲堆棧溢出讓我等待 – squeakcode

0

從我所看到的,您要使用數組($ prisonlist)作爲參數傳遞給jQuery的文本()函數只需要一個字符串,數字,布爾或函數(但不是數組)。

您需要先透過JSON.stringify數組轉換爲字符串:

$('#element).text(JSON.stringify($prisonlist)); 

確保#element心不是輸入或textarea的元素,因爲文本()不能在這些工作(使用VAL( )代替)。