Scripts

javascript: php's print_r() functie in JS.

Simpele javascript snippertje die PHP's print_r() functie nadoet in javascript. Zo kan je array's echo-en voor debug-doeleinden. Voorbeeldtje: input: output: De functie is gemaakt voor gebruik met array's met strings, integers en floats. Niet getest met HTML opjects o.i.d. en daar is ie ook niet voor gemaakt. output type: return. Hij output dus NIET direct naar het scherm, zoals bij de PHP variant. ==== extra: de functie "str_repeat(str,times)" is nodig voor de correcte werking van de functie. Deze functie herhaalt de opgegeven 'str', wat kan zijn 1 teken of een groep tekens, het aantal keer dat opgegeven is in 'times'. bijv. str_repeat(0,4) -> '0000'.

javascript-phps-printr-functie-in-js
[code]<?php

function print_r(array,lfchar,wschar,lvl) {
	if(!wschar) {wschar = '  ';}
	if(!lfchar) {lfchar = '<br/>';}
	if(!lvl) {lvl = 0;}
	var output = '';
	if(typeof(array)=='object') {
		var a=0;
		output += 'array(<br/>';
		lvl++;
		while(a<array.length) {
			output += str_repeat('  ',lvl)+'['+a+'] = '+print_r(array[a],lfchar,wschar,lvl)+'<br/>';
			a++;
		}		
		lvl--;
		output += str_repeat('  ',lvl)+')';
	} else {
		output = array;
	}
	return output;
}

//repeat a string for the given times
function str_repeat(str,times) {
	var a=0;
	output = '';
	str = str.toString();
	while(a<times) {
		output += str;
		a++;
	}
	return output;
}

?>[/code]

[i]i:[/i] kopieer niet de < ?php en ? >. Deze heb ik enkel erbij geplakt voor syntax-highlighting.

Reacties

0
Nog geen reacties.