开发者

Javascript quick variable assignment

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 t开发者_StackOverflow社区o 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];


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

var [x, y] = [1, 2];


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜