4

Possible Duplicate:
Javascript equivalent of PHP's list()

In PHP you can do assignment like this:

list($b,$c,$d) = array("A","B","C");

Is there anything like that in JS?

Community
  • 1
  • 1
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

3 Answers3

2

Yes this is possible since JavaScript 1.7

You can do:

function f() {  
  return [1, 2];  
}  

[a, b] = f();
halfdan
  • 33,545
  • 8
  • 78
  • 87
1

People seem to hate the with() construct in javascript, but anyway...

function f(){return {a:1, b:2};}
with(f()) {
    alert(a);//1
}


// or
function combine(propertyNames, values) {
    var o = {};
    for (var i=0; i<propertyNames.length; i++) {
        o[propertyNames[i]] = values[i];
    }
    return o;
}

with (combine(['a', 'b'], [1, 2])) {
    alert(b);//2
}
goat
  • 31,486
  • 7
  • 73
  • 96
0

I believe that was introduced in JavaScript 1.7. Which means you can't really use it yet in the majority of browsers.

[a,b] = [14,15];
// or
[a,b] = [b,a];
// or
[a,b] = someFuncThatReturnsArray();

See MDN for more details.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241