Javascript equivalent of PHP's list() - php

Really like that function.
$matches = array('12', 'watt');
list($value, $unit) = $matches;
Is there a Javascript equivalent of that?

There is, in 'newer' versions of Javascript: Destructuring assignment - Javascript 1.7. It's probably only supported in Mozilla-based browsers, and maybe in Rhino.
var a = 1;
var b = 3;
[a, b] = [b, a];
EDIT: actually it wouldn't surprise me if the V8 Javascript library (and thus Chrome) supports this. But don't count on it either
Now supported in all modern browsers(except IE, of course).

try this:
matches = ['12', 'watt'];
[value, unit] = matches;

ES6 does support this directly now via array destructuring.
const matches = ['12', 'watt'];
const [value, unit] = matches;

This is my solution for using List/Explode on Javascript.
Fiddle Working Example
First the implementation :
var dateMonth = "04/15";
dateMonth.split("/").list("month","day", "year");
month == "04";
day == "15";
year == null;
It also allows for scoping the new generated variables :
var scoped = (function()
{
var dateMonth = "07/24/2013";
dateMonth.split("/").list("month","day", "year", this);
this.month == "07";
this.day == "24";
this.year == "2013";
})();
This was accomplished by modifying an the Array prototype.
Array.prototype.list = function()
{
var
limit = this.length,
orphans = arguments.length - limit,
scope = orphans > 0 && typeof(arguments[arguments.length-1]) != "string" ? arguments[arguments.length-1] : window
;
while(limit--) scope[arguments[limit]] = this[limit];
if(scope != window) orphans--;
if(orphans > 0)
{
orphans += this.length;
while(orphans-- > this.length) scope[arguments[orphans]] = null;
}
}

There is a experimental implementation of list() by PHPJS here:
https://github.com/kvz/phpjs/blob/master/_experimental/array/list.js

CoffeeScript offers destructuring assignment with the syntax:
[a, b] = someFunctionReturningAnArray()
This is pretty much identical to the feature offered in very new JavaScript versions. However, CoffeeScript produces compiled JS that is compatible even with IE6's JavaScript engine, and therefore it's a good option if compatibility is vital.

Since most JavaScript implementations don't yet support that feature, you could simply do it in a more JavaScript-like fashion:
function list(){
var args = arguments;
return function(array){
var obj = {};
for(i=0; i<args.length; i++){
obj[args[i]] = array[i];
}
return obj;
};
}
Example:
var array = ['GET', '/users', 'UserController'];
var obj = {};
obj = list('method', 'route', 'controller')(array);
console.log(obj.method); // "GET"
console.log(obj.route); // "/users"
console.log(obj.controller); // "UserController"
Check the fiddle
An alternative is to add a list-method to Array.prototype (even I wouldn't recommend it):
Array.prototype.list = function(){
var i, obj = {};
for(i=0; i<arguments.length; i++){
obj[arguments[i]] = this[i];
}
// if you do this, you pass to the dark side `,:,´
this.props = obj;
return obj;
};
Example:
/**
* Example 1: use Array.prototype.props
*/
var array = ['GET', '/users', 'UserController'];
array.list('method', 'route', 'controller');
console.log(array.props.method); // "GET"
console.log(array.props.route); // "/users"
console.log(array.props.controller); // "UserController"
/**
* Example 2: use the return value
*/
var array = ['GET', '/users', 'UserController'];
var props = array.list('method', 'route', 'controller');
console.log(props.method); // "GET"
console.log(props.route); // "/users"
console.log(props.controller); // "UserController"
Check the fiddle for that one

This is my hack at it; as short as I could get it without writing a function to do it. Gotta be careful of the scope of "this" though:
list = ["a","b","c"];
vals = [1,2,3];
for(var i in vals)this[list[i]]=vals[i];
console.log(a,b,c);
Good enough for a laugh. I still assign each variable one at a time:
a=vals[0];
b=vals[1];
c=vals[2];
It's much shorter this way. Besides, if you've got a bunch of variables they should probably be kept in the array, or even better they should be properties of a closure, instead of declaring them all separately.

function list(fn,array){
if(fn.length && array.length){
for(var i=0;i<array.length;i++){
var applyArray = [];
for(var j=0;j<array[i].length;j++){
fn[j] = array[i][j];
applyArray.push(fn[j]);
}
fn.apply(this,applyArray);
}
}
}
Example:
//array array mixture for composure
var arrayMixture = [ ["coffee","sugar","milk"], ["tea","sugar","honey"] ];
//call our function
list(function(treat,addin,addin2){
console.log("I like "+treat+" with " + addin + " and " + addin2);
},arrayMixture);
//output:
//I like coffee with sugar and milk
//I like tea with sugar and honey

Related

shorter way to run functions using its variables

js
var a = 'sun';
var b = 'earth';
var fn = 'some_fn';
$.post('index-pro.php', {fn, a, b}, function(data){
console.log(data);
});
I have a lot of code parts like the above, using different variables, but always refering to index-pro.php as a target file.
index-pro.php
if(isset($_POST)){extract($_POST);}
if(isset($fn) && $fn == 'some_fn'){some_fn($a, $b);}
elseif(isset($fn) && $fn == 'another_fn'){another_fn($another_vars);}
elseif(isset($fn) && $fn == 'another_fn'){another_fn($another_vars);}
How can I say something like this:
whatever fn is set -> run this fn using its variables.
You can call function using not only it's name, but even by a variable, which stores function name:
$fn = 'doStuff';
$a = 2;
$fn($a);
function doStuff($arg) {
echo $arg;
}
If your arguments are different for different functions then I advise to post data as two items: funcName and funcArguments, for example:
$.post('index-pro.php', {funcName: fn, funcArguments: [a, b]}, function(data){
console.log(data);
});
On server side you can do something like (I skip checks and other stuff, just baseline):
$fn = $_POST['funcName'];
$arguments = $_POST['funcArguments'];
// with php5.6/php7 you have variadic `...` syntax
$fn(...$arguments);
// or use plain old `call_user_func_array`:
call_user_func_array($fn, $arguments);
That's what you need. Simple idea: provide an array with arguments to a function name: http://php.net/manual/de/function.call-user-func.php
I didn't tried it out, but this should work:
JS
var a = 'sun';
var b = 'earth';
var fn = 'some_fn';
$.post('index-pro.php', {function: fn, args: [a, b]}, function(data){
console.log(data);
});
PHP
$functionName = $_POST['function'];
$args = $_POST['args'];
call_user_func ($functionName,$args)

Optimization of code in javascripts JSON calls

I've been involved in a large web application where I have a lot of functions that calls web services through JSON. For instance:
/*...*/
refreshClientBoxes: function(customerNr) {
var request = {};
request.method = "getClientBoxes";
request.params = {};
request.params.customerNr = customerNr;
request.id = Math.floor(Math.random() * 101);
postObject(jsonURL, JSON.stringify(request), successClientBoxes);
},
/*...*/
Where “postObject” it’s a function that receive an URL, the data and a callback.
As you can see I have to construct this piece of code in every single method:
var request = {};
request.method = "getClientBoxes";
request.params = {};
request.params.customerNr = customerNr;
request.id = Math.floor(Math.random() * 101);
What's change is the name of the method that we will call and the name and values of parameter that we want to pass.
So I was wondering if there is a way that we can avoid this effort through a method that receive the name of the method that we will call and array of parameters, and using some kind of reflection construct the request parameters and return the request stringifyed.
For the WS I used php + zend 1.12, the MVC framework in JS its ember 0.95 and jQuery.
Edit 1: So thanks all for your answers. What I want it's a way that can give me the name of the parameters that I'm passing to the function or the name of a variable that I passed. Something like this:
var contructRequest = function (methodName, paramList) {
var request = {};
request.method = methodName;
request.params = {};
for(var i = 0; i < paramlist; i++){
/*some how get the paramName through reflection...so if i give a variable called customerNr this "for" add this new parameter to list of parameters like request.params.customerNr = customerNr whatever the variable name is or its value*/
}
request.params[paramName] = paramValue;
request.id = Math.floor(Math.random() * 101);
return request;
}
How about a method like this:
var contructRequest = function (methodName, paramList, paramName, paramValue) {
var request = {};
request.method = methodName;
request.params = paramList;
request.params[paramName] = paramValue;
request.id = Math.floor(Math.random() * 101);
return request;
}
This exploits the fact that object.property can also be referred to using object["property"].
You can call the method like so:
var customerRequest = constructRequest("getClientBoxes", {}, "customerNr", customerNr);
postObject(jsonURL, JSON.stringify(customerRequest), successClientBoxes);
You could DRY this by encapsulating the common parts in a separate function which takes the non-common parts as arguments, and returns the JSON. For example, if we assume that the only parts that change across the different functions are the method and customerNr:
buildRequest(method, customerNr) {
var request = {
method: method,
params: {
customerNr: customerNr
},
id: Math.floor(Math.random() * 101)
};
return JSON.stringify(request);
}
and you'd use it like so:
refreshClientBoxes: function(customerNr) {
var json = buildRequest('getClientBoxes', customerNr);
postObject(jsonURL, json, successClientBoxes);
},

Is there a function in javascript similar to compact from php?

I found compact function very useful (in php). Here is what it does:
$some_var = 'value';
$ar = compact('some_var');
//now $ar is array('some_var' => 'value')
So it create array from variables which you specify, when key for elements is variable name.
Is there any kind of function in javascript ?
You can use ES6/ES2015 Object initializer
Example:
let bar = 'bar', foo = 'foo', baz = 'baz'; // declare variables
let obj = {bar, foo, baz}; // use object initializer
console.log(obj);
{bar: 'bar', foo: 'foo', baz: 'baz'} // output
Beware of browsers compatibilities, you always can use Babel
No there is no analogous function nor is there any way to get variable names/values for the current context -- only if they are "global" variables on window, which is not recommended. If they are, you could do this:
function compact() {
var obj = {};
Array.prototype.forEach.call(arguments, function (elem) {
obj[elem] = window[elem];
});
return obj;
}
You can also use phpjs library for using the same function in javascript same as in php
Example
var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld';
compact('var1', 'var2', 'var3');
Output
{'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'}
If the variables are not in global scope it is still kinda possible but not practical.
function somefunc() {
var a = 'aaa',
b = 'bbb';
var compact = function() {
var obj = {};
for (var i = 0; i < arguments.length; i++) {
var key = arguments[i];
var value = eval(key);
obj[key] = value;
}
return obj;
}
console.log(compact('a', 'b')) // {a:'aaa',b:'bbb'}
}
The good news is ES6 has a new feature that will do just this.
var a=1,b=2;
console.log({a,b}) // {a:1,b:2}

Magic Methods in JavaScript [duplicate]

Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.
My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.
The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.
Proxy can do it! I'm so happy this exists!! An answer is given here: Is there a javascript equivalent of python's __getattr__ method? . To rephrase in my own words:
var x = new Proxy({}, {
get(target, name) {
return "Its hilarious you think I have " + name
}
})
console.log(x.hair) // logs: "Its hilarious you think I have hair"
Proxy for the win! Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
You can combine proxy and class to have a nice looking code like php:
class Magic {
constructor () {
return new Proxy(this, this);
}
get (target, prop) {
return this[prop] || 'MAGIC';
}
}
this binds to the handler, so you can use this instead of target.
Note: unlike PHP, proxy handles all prop access.
let magic = new Magic();
magic.foo = 'NOT MAGIC';
console.log(magic.foo); // NOT MAGIC
console.log(magic.bar); // MAGIC
You can check which browsers support proxy http://caniuse.com/#feat=proxy.
The closest you can find is __noSuchMethod__ (__noSuchMethod__ is deprecated), which is JavaScript's equivalent of PHP's __call().
Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.
var foo = {
__noSuchMethod__ : function(id, args) {
alert(id);
alert(args);
}
};
foo.bar(1, 2);
Javascript 1.5 does have getter/setter syntactic sugar. It's explained very well by John Resig here
It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).
If you really need an implementation that works, you could "cheat" your way arround by testing the second parameter against undefined, this also means you could use get to actually set parameter.
var foo = {
args: {},
__noSuchMethod__ : function(id, args) {
if(args === undefined) {
return this.args[id] === undefined ? this[id] : this.args[id]
}
if(this[id] === undefined) {
this.args[id] = args;
} else {
this[id] = args;
}
}
};
If you're looking for something like PHP's __get() function, I don't think Javascript provides any such construct.
The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each.
In dodgy pseudo-ish code:
for (o in this) {
if (this.hasOwnProperty(o)) {
this['get_' + o] = function() {
// return this.o -- but you'll need to create a closure to
// keep the correct reference to "o"
};
}
}
I ended up using a nickfs' answer to construct my own solution. My solution will automatically create get_{propname} and set_{propname} functions for all properties. It does check if the function already exists before adding them. This allows you to override the default get or set method with our own implementation without the risk of it getting overwritten.
for (o in this) {
if (this.hasOwnProperty(o)) {
var creategetter = (typeof this['get_' + o] !== 'function');
var createsetter = (typeof this['set_' + o] !== 'function');
(function () {
var propname = o;
if (creategetter) {
self['get_' + propname] = function () {
return self[propname];
};
}
if (createsetter) {
self['set_' + propname] = function (val) {
self[propname] = val;
};
}
})();
}
}
This is not exactly an answer to the original question, however this and this questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did.
Coming from Python, what I was looking for was an equivalent of obj.__getattr__(key)and obj.__hasattr__(key) methods. What I ended up using is:
obj[key] for getattr and obj.hasOwnProperty(key) for hasattr (doc).
It is possible to get a similar result simply by wrapping the object in a getter function:
const getProp = (key) => {
const dictionary = {
firstName: 'John',
lastName: 'Doe',
age: 42,
DEFAULT: 'there is no prop like this'
}
return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]);
}
console.log(getProp('age')) // 42
console.log(getProp('Hello World')) // 'there is no prop like this'

Is there an equivalent for var_dump (PHP) in Javascript?

We need to see what methods/fields an object has in Javascript.
As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.
If Firebug isn't an option for you, then try this simple script:
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".
If you are using firefox then the firebug plug-in console is an excellent way of examining objects
console.debug(myObject);
Alternatively you can loop through the properties (including methods) like this:
for (property in object) {
// do what you want with property, object[property].value
}
A lot of modern browsers support the following syntax:
JSON.stringify(myVar);
It can't be stated enough that you can use console.debug(object) for this. This technique will save you literally hundreds of hours a year if you do this for a living :p
To answer the question from the context of the title of this question, here is a function that does something similar to a PHP var_dump. It only dumps one variable per call, but it indicates the data type as well as the value and it iterates through array's and objects [even if they are Arrays of Objects and vice versa]. I'm sure this can be improved on. I'm more of a PHP guy.
/**
* Does a PHP var_dump'ish behavior. It only dumps one variable per call. The
* first parameter is the variable, and the second parameter is an optional
* name. This can be the variable name [makes it easier to distinguish between
* numerious calls to this function], but any string value can be passed.
*
* #param mixed var_value - the variable to be dumped
* #param string var_name - ideally the name of the variable, which will be used
* to label the dump. If this argumment is omitted, then the dump will
* display without a label.
* #param boolean - annonymous third parameter.
* On TRUE publishes the result to the DOM document body.
* On FALSE a string is returned.
* Default is TRUE.
* #returns string|inserts Dom Object in the BODY element.
*/
function my_dump (var_value, var_name)
{
// Check for a third argument and if one exists, capture it's value, else
// default to TRUE. When the third argument is true, this function
// publishes the result to the document body, else, it outputs a string.
// The third argument is intend for use by recursive calls within this
// function, but there is no reason why it couldn't be used in other ways.
var is_publish_to_body = typeof arguments[2] === 'undefined' ? true:arguments[2];
// Check for a fourth argument and if one exists, add three to it and
// use it to indent the out block by that many characters. This argument is
// not intended to be used by any other than the recursive call.
var indent_by = typeof arguments[3] === 'undefined' ? 0:arguments[3]+3;
var do_boolean = function (v)
{
return 'Boolean(1) '+(v?'TRUE':'FALSE');
};
var do_number = function(v)
{
var num_digits = (''+v).length;
return 'Number('+num_digits+') '+v;
};
var do_string = function(v)
{
var num_chars = v.length;
return 'String('+num_chars+') "'+v+'"';
};
var do_object = function(v)
{
if (v === null)
{
return "NULL(0)";
}
var out = '';
var num_elem = 0;
var indent = '';
if (v instanceof Array)
{
num_elem = v.length;
for (var d=0; d<indent_by; ++d)
{
indent += ' ';
}
out = "Array("+num_elem+") \n"+(indent.length === 0?'':'|'+indent+'')+"(";
for (var i=0; i<num_elem; ++i)
{
out += "\n"+(indent.length === 0?'':'|'+indent)+"| ["+i+"] = "+my_dump(v[i],'',false,indent_by);
}
out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
return out;
}
else if (v instanceof Object)
{
for (var d=0; d<indent_by; ++d)
{
indent += ' ';
}
out = "Object \n"+(indent.length === 0?'':'|'+indent+'')+"(";
for (var p in v)
{
out += "\n"+(indent.length === 0?'':'|'+indent)+"| ["+p+"] = "+my_dump(v[p],'',false,indent_by);
}
out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
return out;
}
else
{
return 'Unknown Object Type!';
}
};
// Makes it easier, later on, to switch behaviors based on existance or
// absence of a var_name parameter. By converting 'undefined' to 'empty
// string', the length greater than zero test can be applied in all cases.
var_name = typeof var_name === 'undefined' ? '':var_name;
var out = '';
var v_name = '';
switch (typeof var_value)
{
case "boolean":
v_name = var_name.length > 0 ? var_name + ' = ':''; // Turns labeling on if var_name present, else no label
out += v_name + do_boolean(var_value);
break;
case "number":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + do_number(var_value);
break;
case "string":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + do_string(var_value);
break;
case "object":
v_name = var_name.length > 0 ? var_name + ' => ':'';
out += v_name + do_object(var_value);
break;
case "function":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + "Function";
break;
case "undefined":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + "Undefined";
break;
default:
out += v_name + ' is unknown type!';
}
// Using indent_by to filter out recursive calls, so this only happens on the
// primary call [i.e. at the end of the algorithm]
if (is_publish_to_body && indent_by === 0)
{
var div_dump = document.getElementById('div_dump');
if (!div_dump)
{
div_dump = document.createElement('div');
div_dump.id = 'div_dump';
var style_dump = document.getElementsByTagName("style")[0];
if (!style_dump)
{
var head = document.getElementsByTagName("head")[0];
style_dump = document.createElement("style");
head.appendChild(style_dump);
}
// Thank you Tim Down [http://stackoverflow.com/users/96100/tim-down]
// for the following addRule function
var addRule;
if (typeof document.styleSheets != "undefined" && document.styleSheets) {
addRule = function(selector, rule) {
var styleSheets = document.styleSheets, styleSheet;
if (styleSheets && styleSheets.length) {
styleSheet = styleSheets[styleSheets.length - 1];
if (styleSheet.addRule) {
styleSheet.addRule(selector, rule)
} else if (typeof styleSheet.cssText == "string") {
styleSheet.cssText = selector + " {" + rule + "}";
} else if (styleSheet.insertRule && styleSheet.cssRules) {
styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
}
}
};
} else {
addRule = function(selector, rule, el, doc) {
el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
};
}
// Ensure the dump text will be visible under all conditions [i.e. always
// black text against a white background].
addRule('#div_dump', 'background-color:white', style_dump, document);
addRule('#div_dump', 'color:black', style_dump, document);
addRule('#div_dump', 'padding:15px', style_dump, document);
style_dump = null;
}
var pre_dump = document.getElementById('pre_dump');
if (!pre_dump)
{
pre_dump = document.createElement('pre');
pre_dump.id = 'pre_dump';
pre_dump.innerHTML = out+"\n";
div_dump.appendChild(pre_dump);
document.body.appendChild(div_dump);
}
else
{
pre_dump.innerHTML += out+"\n";
}
}
else
{
return out;
}
}
You want to see the entire object (all nested levels of objects and variables inside it) in JSON form. JSON stands for JavaScript Object Notation, and printing out a JSON string of your object is a good equivalent of var_dump (to get a string representation of a JavaScript object). Fortunately, JSON is very easy to use in code, and the JSON data format is also pretty human-readable.
Example:
var objectInStringFormat = JSON.stringify(someObject);
alert(objectInStringFormat);
console.dir (toward the bottom of the linked page) in either firebug or the google-chrome web-inspector will output an interactive listing of an object's properties.
See also this Stack-O answer
If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.
A bit of improvement on nickf's function for those that don't know the type of the variable coming in:
function dump(v) {
switch (typeof v) {
case "object":
for (var i in v) {
console.log(i+":"+v[i]);
}
break;
default: //number, string, boolean, null, undefined
console.log(typeof v+":"+v);
break;
}
}
I improved nickf's answer, so it recursively loops through objects:
function var_dump(obj, element)
{
var logMsg = objToString(obj, 0);
if (element) // set innerHTML to logMsg
{
var pre = document.createElement('pre');
pre.innerHTML = logMsg;
element.innerHTML = '';
element.appendChild(pre);
}
else // write logMsg to the console
{
console.log(logMsg);
}
}
function objToString(obj, level)
{
var out = '';
for (var i in obj)
{
for (loop = level; loop > 0; loop--)
{
out += " ";
}
if (obj[i] instanceof Object)
{
out += i + " (Object):\n";
out += objToString(obj[i], level + 1);
}
else
{
out += i + ": " + obj[i] + "\n";
}
}
return out;
}
console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');
These Should work correctly On Google Chrome and Mozilla Firefox (if you are running with old version of firefox, so you have to install Firebug plugin)
On Internet Explorer 8 or higher you must do as follow:
Launch "Developer Tools, by clicking on F12 Button
On the Tab List, click on "Script" Tab"
Click on "Console" Button in the right side
For more informations you can visit this URL: https://developer.chrome.com/devtools/docs/console-api
You can simply use the NPM package var_dump
npm install var_dump --save-dev
Usage:
const var_dump = require('var_dump')
var variable = {
'data': {
'users': {
'id': 12,
'friends': [{
'id': 1,
'name': 'John Doe'
}]
}
}
}
// print the variable using var_dump
var_dump(variable)
This will print:
object(1) {
["data"] => object(1) {
["users"] => object(2) {
["id"] => number(12)
["friends"] => array(1) {
[0] => object(2) {
["id"] => number(1)
["name"] => string(8) "John Doe"
}
}
}
}
}
Link: https://www.npmjs.com/package/#smartankur4u/vardump
Thank me later!
If you are looking for PHP function converted in JS, there is this little site: http://phpjs.org.
On there you can get most of the PHP function reliably written in JS. for var_dump try: http://phpjs.org/functions/var_dump/ (make sure to check the top comment, this depends on "echo", which can also be downloaded from the same site)
I used the first answer, but I felt was missing a recursion in it.
The result was this:
function dump(obj) {
var out = '';
for (var i in obj) {
if(typeof obj[i] === 'object'){
dump(obj[i]);
}else{
out += i + ": " + obj[i] + "\n";
}
}
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
Based on previous functions found in this post.
Added recursive mode and indentation.
function dump(v, s) {
s = s || 1;
var t = '';
switch (typeof v) {
case "object":
t += "\n";
for (var i in v) {
t += Array(s).join(" ")+i+": ";
t += dump(v[i], s+3);
}
break;
default: //number, string, boolean, null, undefined
t += v+" ("+typeof v+")\n";
break;
}
return t;
}
Example
var a = {
b: 1,
c: {
d:1,
e:2,
d:3,
c: {
d:1,
e:2,
d:3
}
}
};
var d = dump(a);
console.log(d);
document.getElementById("#dump").innerHTML = "<pre>" + d + "</pre>";
Result
b: 1 (number)
c:
d: 3 (number)
e: 2 (number)
c:
d: 3 (number)
e: 2 (number)
Here is my solution. It replicates the behavior of var_dump well, and allows for nested objects/arrays. Note that it does not support multiple arguments.
function var_dump(variable) {
let out = "";
let type = typeof variable;
if(type == "object") {
var realType;
var length;
if(variable instanceof Array) {
realType = "array";
length = variable.length;
} else {
realType = "object";
length = Object.keys(variable).length;
}
out = `${realType}(${length}) {`;
for (const [key, value] of Object.entries(variable)) {
out += `\n [${key}]=>\n ${var_dump(value).replace(/\n/g, "\n ")}\n`;
}
out += "}";
} else if(type == "string") {
out = `${type}(${type.length}) "${variable}"`;
} else {
out = `${type}(${variable.toString()})`;
}
return out;
}
console.log(var_dump(1.5));
console.log(var_dump("Hello!"));
console.log(var_dump([]));
console.log(var_dump([1,2,3,[1,2]]));
console.log(var_dump({"a":"b"}));
Late to the game, but here's a really handy function that is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP
Note, you can use tags as well by passing 'TAG-YourTag' and it will be applied until another tag is read, for example, 'TAG-YourNextTag'
/*
* Brief: Print to console.log() from PHP
* Description: Print as many strings,arrays, objects, and other data types to console.log from PHP.
* To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
* you can pass as many data as you want an this will still work.
*
* This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*
* A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
* detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
* be applied to all data after it.
*
* Example:
* consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3);
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
$tag = substr($arg,4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('".$tag." ".$arg."');</script>";
}
}
}
}
NOTE: func_num_args() and func_num_args() are php functions for reading a dynamic number of input args, and allow this function to have infinitely many console.log requests from one function call
The following is my favorite var_dump/print_r equivalent in Javascript to PHPs var_dump.
function dump(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 += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
I just want to add something relatively important about console.log
If you are debugging large variables (like large audio or video data buffers). When you print console.log(big_variable) the console will only display a small part of it. (it seems a bit obvious).
If however, the variable is in a loop and this variable is constantly changing, if you ever "copy it into your clipboard" , what the browser will do is to ask for the variable AGAIN (and that may have changed by the time you are copying).
I'll tell you my story. I am programming an app that deals with big chunks of audio data, with Float32arrays of size 8192. If the buffer had certain characteristics, I would print the variable using console.log() and then grab that variable to test and toy around and play with it (and even use it for mocks so I can do automated testing)
However, the results would never hold. The mic would capture the audio data, store it on a this.audioBuffer variable and the whole thing would work, but when I copied that exact variable from console.log so I could us it as a mock to run some automated tests, the behaviour would change dramatically.
It took me a while to figure this out, Apparently, whenever i "copied" or "set the variable as global" in the debugger, rather than copying the variables displayed in console.log, the jsvm would ask for the this.audioBuffer again. and since the variable was being used inside of a loop, the microphone would still record and I would get a completely different sound array than what I was listening to and thought the audio buffer was in the first place.
If you are dealing with large complex data structures like audio or video files, image files... and these are subject to change when you are reading the values in the chrome /firefox / edge console, make sure you don't console.log(variable), but rather console.log(JSON.stringify(variable)). it will save you a ton of time
you can use this for strings and objects/array
function print_r(obj){
return JSON.stringify(obj, null, "\t");
}

Categories