A function example of JS print array

Source: Internet
Author: User

In JS, unlike PHP, it has a print_r (), var_dump () function that prints an array. In order to facilitate day-to-day debugging, we can write a printed function of their own, just like PHP.


Implementation is not difficult, the main use of loops to traverse the array, while using Object.prototype.toString.call to determine if the element is still an array, then recursive execution.

The following is a printed effect chart that you can choose to print with alert, or you can choose to print to the console with Console.log. The printed effect is similar to the Print_r in PHP.

Effect 1

Can be printed to the console

Effect 2

Reference Source:

<!doctype html>

<meta charset= "Utf-8" >

<title>js Print Array Function Example </title>

<body>

<script type= "Text/javascript" >

var arr = new Array (' www.111cn.com ');

ARR[1] = new Array (' www ', ' 111cn ', ' com ');

Arrres = Print_arr (arr);

alert (arrres); Eject directly

Console.log (Arrres); Print on console

/**

* Print Array

* @param {[type]} arr the array to print

* @param {[type]} space controls the indentation of printing

* @param {[type]} space2 control print indentation 2

*/

function Print_arr (arr, space, Space2)

{

Space = Space | | '';

Space2 = Space2 | | '      ';

var str = "array\n" +space+ "(\ n";

for (var i=0; i<arr.length; i++)

{

if (Object.prototype.toString.call (arr[i]) = = ' [Object Array] ')

{//Judge whether it is an array, if it is, perform a recursive concatenation

str = space2 + ' [' +i+ '] => ' + Print_arr (arr[i], space+ ', space2+ ');

}

Else

{

str = + Space2 + ' [' +i+ '] => ' + arr[i] + ' \ n ';

}

}

STR + + space+ ") \ n";

return str;

}

</script>

</body>

This function can be placed in the public JS file, the day-to-day work is very convenient to invoke debugging.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.