Is there an easier way to send the variable name and content to the console?

I often need to monitor the contents of variables when testing such programs:

var anObject = {aProperty:true}; // this is just an example.

console.log('anObject.aProperty: ' + anObject.aProperty);  <-- typed it twice.

I enter the variable name into a string and then type the same again to refer to the value.

It seems that unnecessary duplication in order to write the same thing twice every time. Is there a way to do this by simply spelling the name once with a function?

For instance:

function show(value) {
  console.log("'" + ??? + "':" + value):
}  

so it can be used like this (or something similar):

   show(anObject.aProperty);

The above example is a simple example. Basically, I ask if there is a way to get the name of the variable that was passed to the function so that the name can then be displayed as part of a string showing the value of the variable.

+4
source share
3

:

http://jsfiddle.net/coma/6HTnB/

var anObject = {
    aProperty: ['uno', 'dos', 'tres']
};

var log = function(object, property) {

    var evil = 'object.' + property;

    console.log(evil, eval(evil));
};

log(anObject, 'aProperty[2]');

:

http://jsfiddle.net/coma/6HTnB/2/

var anObject = {
    aProperty: ['uno', 'dos', 'tres']
};

var show = function(a) {

    console.log(a + ':', eval(a));
};

show('anObject.aProperty[2]');

, eval - , , , .

+1

​​ show():

function show(object, property) {
    console.log(property + ":", object[property]);
}

:

var mouse = { x: 100, y: 200 };
show(mouse, 'x');

: http://jsfiddle.net/IQAndreas/c9SUm/


( - , JavaScript, ), , . , :

var mouse = { x: 100, y: 200 };
console.log("== mouse ==");
show(mouse, 'x');
show(mouse, 'y');

:

"== mouse =="
"x:" 100
"y:" 200

, ( JavaScript, , {}, Object):

function show(object, property) {
    var className = object.constructor.name;
    console.log(className + "#" + property + ":", object[property]);
}

( , Mouse):

"Mouse#x:" 100
"Mouse#y:" 200

: http://jsfiddle.net/IQAndreas/c9SUm/2/

+1

Based on a coma, I think this might be a solution:

function show() {
    return function (value) {
        console.log(value + ':', eval(value));
    };
};

function aTest() {
   obj = {x:1, y:2};            show()('obj');
};

function bTest() {
   obj = {x:3, y:4};            show()('obj');
};

aTest(); // obj: { x: 1, y: 2 }
bTest(); // obj: { x: 3, y: 4 }
0
source

Source: https://habr.com/ru/post/1536275/


All Articles