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

后端 未结 4 655
醉梦人生
醉梦人生 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:00

    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}
    

提交回复
热议问题