110

How can I view the structure of an array in JavaScript using alert()?

Brett DeWoody
  • 50,328
  • 25
  • 121
  • 168
pppttt
  • 1,097
  • 2
  • 7
  • 3

11 Answers11

124

A very basic approach is alert(arrayObj.join('\n')), which will display each array element in a row.

Humberto
  • 6,861
  • 2
  • 28
  • 45
  • 5
    This works great. Replace "arrayObj" with the name of your array. So if your array is named myArray, this is your line of code: `alert(myArray.join('\n'));` – Tony Brasunas Oct 21 '14 at 23:32
54

EDIT: Firefox and Google Chrome now have a built-in JSON object, so you can just say alert(JSON.stringify(myArray)) without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON object being present in all browsers, but for debugging purposes it's incredibly useful.

I tend to use the jQuery-json plugin as follows:

alert( $.toJSON(myArray) );

This prints the array in a format like

[5, 6, 7, 11]

However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.

Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.

Eli Courtwright
  • 164,889
  • 61
  • 203
  • 255
32

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
YetAnotherUser
  • 8,490
  • 3
  • 36
  • 52
Fawad Ghafoor
  • 5,029
  • 5
  • 38
  • 53
16

You can use alert(arrayObj.toSource());

Piseth Sok
  • 1,581
  • 1
  • 18
  • 23
  • 1
    Works under Firefox, but not under Safari or MSIE, see http://stackoverflow.com/questions/1101584/javascript-tosource-method-not-working – Julien Kronegg Dec 20 '12 at 14:24
8

I'd recommend using toString().

Ex. alert(array.toString()), or console.log(array.toString())

dk123
  • 15,184
  • 16
  • 63
  • 74
3

If this is for debugging purposes, I would advise you use a JavaScript debugger such as Firebug. It will let you view the entire contents of arrays and much more, including modifying array entries and stepping through code.

Justin Ethier
  • 122,367
  • 49
  • 219
  • 273
3

For readability purposes you can use:

alert(JSON.stringify(someArrayOrObj, '', 2));

More about JSON.stringify().

Example:

let user = {
  name: "John",
  age: 30,
  roles: {
    isAdmin: false,
    isEditor: true
  }
};

alert(JSON.stringify(user, "", 2));
/* Result:
{
  "name": "John",
  "age": 30,
  "roles": {
    "isAdmin": false,
    "isEditor": true
  }
} 
*/
Victor S.
  • 1,430
  • 1
  • 18
  • 24
2

If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.

Here is an example:

//-------------------------------------------------------------------
// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
    // Sets the point coordinates depending on the parameters defined
    switch (arguments.length) {
        case 0:
            this.x = null;
            this.y = null;
            break;
        case 1:
            this.x = CoordenadaX;
            this.y = null;
            break;
        case 2:
            this.x = CoordenadaX;
            this.y = CoordenadaY;
            break;
    }
    // This adds the toString Method to the point object so the 
    // point can be printed using alert();
    this.toString = function() {
        return " (" + this.x + "," + this.y + ") ";
    };
 }

Then if you have an array of points:

var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );

You can print simply calling:

alert(MyArray);

Hope this helps!

tomasofen
  • 1,252
  • 1
  • 11
  • 16
1

Better use Firebug (chrome console etc) and use console.dir()

yAnTar
  • 3,609
  • 9
  • 41
  • 64
1

You could write a function that will convert and format this array as string. Even better: use FireBug for debugging instead of alerts.

Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
-5
alert($("#form_id").serialize());
karthikr
  • 87,486
  • 24
  • 182
  • 182
  • 3
    The question is tagged `javascript` which says "Unless a tag for a framework/library is also included, a pure JavaScript answer is expected". Even if that wasn't the case… the question is asking about an array, not an HTML form. – Quentin Jul 18 '13 at 21:44