Get variable names with JavaScript

前端 未结 7 979
傲寒
傲寒 2021-02-08 18:47

I want to create a log function where I can insert variable names like this:

var a = \'123\',
    b = \'abc\';

log([a, b]);

And the result sho

7条回答
  •  庸人自扰
    2021-02-08 19:24

    You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:

    var x = 7;
    var y = 8;
    
    function logVars(arr){
        for(var i = 0; i < arr.length; i++){
            alert(arr[i] + " = " + window[arr[i]]);
        }
    }
    
    logVars(["x","y"]);
    

提交回复
热议问题