简体   繁体   中英

How do I display the Var name of a variable instead of the value that Var hold in javascript?

So I am trying to build myself a debugger. Here is how I want the output to look:

kills:    7
level:    60
weapon:   sniper

These values will be displayed in a black rectangle that can be dragged around the screen using the mouse. Here is what is does so far. (I have cut out all visuals except the Text command) Note: I am using Khan academy, so the code will look slightly different.

var kills = 0; 
var level = 10;         
var weapon = 'sniper';

var input = [kills,level,weapon];  
var debug1 = function(data){
    for(var i = 0; i < data.length; i ++){
        text(data[i],mouseX + (i*30) + 4,mouseY - 75);
    }

};

var draw = function() {
    debug1(input); 
};

Code explanation: The Vars at the top are just sample Vars. I want debug1(){}; to be able to take any and all vars. What my output results look like (compare to what I want them to look like):

0
60
sniper

My problem: I cannot find a way to print out the bar names to the screen! In my formatted print I want the Var name associated with the data it holds. but whenever (and however) I try and print in the var name I always end up with its value. This makes my debugger useless, because even though it prints out values, I cant tell what vars the data is connected with. Please help me by showing a way to do this! Things I have tried:

data[i].text

"data[i]"

do you have the option of making the data an associative array ie

input = [Kills: kills, Level: level, Weapon: weapon] 

so you can refer to them as Key/Val pairs? You could then use something like

$.each(data, function(key, value) {
    text(key + ': '+ value,mouseX + (i*30) + 4,mouseY - 75);
});

that could be one way to work it out (havent tested it yet, but it seems straight forward)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM