简体   繁体   English

Javascript 快速变量赋值

[英]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 to values. Python 提供了一些非常简单的语句,用于快速将 arrays 分配给值。 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 .例如,如果我有一个盒子作为数组,比如box=[0,0,100,100]我可以分配这些点,比如x1,y1,x2,y2=box Is there such a statement in javascript? javascript中有这样的说法吗? This would be especially useful in class functions where var x1,y1,x2,y2=this.box would be much less verbose than这在 class 函数中特别有用,其中var x1,y1,x2,y2=this.box

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?如果是这样,那么是否有任何 javascript 方法将此应用于 for 循环? Coming from python, the below just seems so intuitive来自 python,下面看起来很直观

boxes=[[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]]盒子=[[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: Firefox 实现了新语法,但目前没有其他浏览器这样做:

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

I believe that's a no go.. Alternatively, you could generate your list as我相信那不是 go .. 或者,您可以将列表生成为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM