4

This is one of those questions I don't know how to properly word so I appologize if it has been asked before.

Python provides some very simple statements for quickly assigning arrays to values. For example if I have a box as an array like so box=[0,0,100,100] I can assign those points like so x1,y1,x2,y2=box. Is there such a statement in javascript? This would be especially useful in class functions where var x1,y1,x2,y2=this.box would be much less verbose than

var x1=this.box[0];
var y1=this.box[1];
var x2=this.box[2];
var y2=this.box[3];

If so, then are there any javascript methods that apply this to for loops? Coming from python, the below just seems so intuitive

boxes=[[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]]

for box in boxes:
 x1,x2,x3,x4 = box
 #do something

definitely more intuitive than

var boxes=[[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]];

    for (var i = 0; i < boxes.length : i++){
      var box = boxes[i];
      var x1 = box[0];
      var y1 = box[1];
      var x2 = box[2];
      var y2 = box[3];
4
  • PHP (list) and Perl have it too. Javascript doesn't. Commented May 27, 2011 at 9:20
  • FYI its call destructured assignment and in in js 1.7 (developer.mozilla.org/en/…) Commented May 27, 2011 at 9:30
  • @Alex: Thanks. It's, in my opinion, not as clean as in Python, but it definitely helps Commented May 27, 2011 at 9:41
  • @Alex, another example is default values. I really could use default values in function parameters. Commented May 27, 2011 at 19:01

2 Answers 2

4

Cross browser it isn't possible, sorry. Firefox implements a new syntax, but no other browser currently does:

var [x, y] = [1, 2];
Sign up to request clarification or add additional context in comments.

3 Comments

This is new javascript syntax, as far as I know 1.7. Sadly the support isn't available.
Such a pitty, this is one of the cases where I don't think JS has made a good design decision
Note that plenty of people rave about coffeescript: jashkenas.github.com/coffee-script, which compiles down to JS. It supports the above syntax.
1

I believe that's a no go.. Alternatively, you could generate your list as

var boxes = [
   {'x1':0, 'y1':0, 'x2':100, 'y2':100},
   {'x1':0, 'y1':0, 'x2':100, 'y2':100},
   {'x1':0, 'y1':0, 'x2':100, 'y2':100},
]

Then you can access them with

for (i in boxes) {
   var box = boxes[i]
   // use box.x1 box.y1 box.x2 box.y2
   //such as:
   console.log(box.x1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.