Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript create local object on return statement

Tags:

javascript

Is there a way to make this function not create a global variable while the body is still just an expression on one line (after return).

Seems like if it works with making a global, should be a way to do it with a local

getHashKeyValues = function(h){
    return p={},h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v}),p
}

console.log(getHashKeyValues("#/app/path|key1=value1;key2=value2"))
like image 234
AwokeKnowing Avatar asked Jun 20 '26 01:06

AwokeKnowing


2 Answers

You can declare p as a function parameter:

getHashKeyValues = function(h,p){
    return p={},h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v}),p
};

That will make p a local variable in the function just like if you declared it with var. It is perfectly valid to call that function with only one argument, p will just be undefined until it gets assigned a value.

like image 60
Paul Avatar answered Jun 21 '26 15:06

Paul


Declare p as a var in the function.

getHashKeyValues = function(h) {
    var p = {};
    h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v});
    return p;
}

And make it readable–this is an awful way to write this.

Edit Oh, I missed the "one line" requirement, which disqualifies my answer.

Even though I'm right :p

like image 41
Dave Newton Avatar answered Jun 21 '26 14:06

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!