在 JavaScript 中将数组解包为单独的变量 [英] Unpacking array into separate variables in JavaScript

查看:112
本文介绍了在 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:

let [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;

您也可以创建一个默认值:

You could also create a default value:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one); // 1
console.log(two); // 2
console.log(three); // 'three'

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

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