开箱数组在JavaScript中不同的变量 [英] Unpacking array into separate variables in JavaScript

查看:135
本文介绍了开箱数组在JavaScript中不同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题,我已经这样做。我只是不记得如何,或究竟它被称为

This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

在Python中我可以这样做:

In python I can do this:

arr = ['one', 'two']
one, two = arr

如何做到这一点在JavaScript中?

how do I do that in JavaScript?

推荐答案

这是目前AFAIK唯一的跨浏览器兼容的解决方案:

This is currently the only cross-browser-compatible solution AFAIK:

var one = arr[0],
    two = arr[1];


ES6将使解构赋值:


ES6 will allow destructuring assignment:

var [x, y] = ['foo', 'bar'];
console.log(x); // 'foo'
console.log(y); // 'bar'

或者,要坚持你最初的例子:

Or, to stick to your initial example:

var arr = ['one', 'two'];
var [one, two] = arr;

这篇关于开箱数组在JavaScript中不同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆