如何在JavaScript中提取数组键到变量?

时间:2018-09-17 08:40:15

标签: javascript node.js ecmascript-6 extract

我有一个像数据一样的数组/对象,我想像下面这样的变量来访问数组/对象的每个键:

var data = {};
data['one'] = 1;
data['tow'] = 2;

console.log(one);

我希望输出为:1
Php可以使用提取(数据)来实现。我该如何在javascript中做到这一点?

2 个答案:

答案 0 :(得分:2)

您需要对象或地图:

const data = {}
data['one'] = 1
data['two'] = 2

console.log(data['one'])

const data2 = new Map()
data2.set('one', 1)
data2.set('two', 2)

console.log(data2.get('one'))

此外,与extract的近似值是解构

const data = {}
data['one'] = 1
data['two'] = 2

const { one, two } = data

console.log('Destructured from an object: ', one, two)

const data2 = new Map()
data2.set('one', 1)
data2.set('two', 2)

const [[, one2], [, two2]] = data2
const [one3, two3] = data2.values()

console.log('Destructured from map entries: ', one2, two2)
console.log('Destructured from map values: ', one3, two3)

答案 1 :(得分:1)

在Javascript中,您使用{}创建关联数组。如下所示:

var data = {}
data['one'] = 1;
data['two'] = 2;

console.log(data['one'])

或者您可以使用点符号:

data.one = 1;
data.two = 2;

console.log(data.one)