Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I view array structure in JavaScript with alert()?

Tags:

javascript

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

like image 913
pppttt Avatar asked Jun 09 '10 14:06

pppttt


People also ask

How do you read an array in JavaScript?

An item in a JavaScript array is accessed by referring to the index number of the item in square brackets. We know 0 will always output the first item in an array. We can also find the last item in an array by performing an operation on the length property and applying that as the new index number.

How do I see all the elements in an array?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.

How do you view an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


2 Answers

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

like image 151
Humberto Avatar answered Sep 29 '22 10:09

Humberto


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.

like image 42
Eli Courtwright Avatar answered Sep 29 '22 09:09

Eli Courtwright