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

后端 未结 4 616
醉梦人生
醉梦人生 2021-01-18 15:24

I found compact function very useful (in php). Here is what it does:

$some_var = \'value\';
$ar = compact(\'some_var\');
//now $ar is array(\'so         


        
4条回答
  •  情话喂你
    2021-01-18 16:07

    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;
    }
    

提交回复
热议问题