squeakcode
squeakcode

Reputation: 3

Undefined Array in JQuery/JavaScript

I'm having some trouble with the following piece of code:

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

I would like to be able to view the contents of $prisonlist (or $prisonlist[some value]) in the console, and to display it in the text of the div. Essentially, whenever I do, it comes up with an error known as "undefined" - although my other functions that work with it seem to work just fine (such as the //

Code:

        $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
                        }

                });

Upvotes: 0

Views: 62

Answers (2)

jsdeveloper
jsdeveloper

Reputation: 4045

From what i can see, you are trying to use an array ($prisonlist) as an argument to the jquery text() function which only takes a string, number, boolean or function (but not an array).

You need to cast the array to a string first using JSON.stringify:

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

Ensure that #element isnt an input or textarea element since text() doesn't work on those (use val() instead).

Upvotes: 0

avnr
avnr

Reputation: 666

The declaration var $prisonlist=[];is scoped, therefore unavailable in the console where you can see only global stuff. The solutions are:

  • Quick yet ugly - declare $prisonlist=[]; (without the var) in the global scope.

  • My preferred - wherever you want to inspect the variable insert console.log($prisonlist). This will log the current value of the variable to the console.

  • Use a debugger

Upvotes: 2

Related Questions