简体   繁体   English

如何在新的JS哈希表中使用变量作为键

[英]How can I use a variable as a key in a new JS hashtable

Is there a way in javascript that I can use variables in new hashtables as keys 在javascript中是否有一种方法可以将新哈希表中的变量用作键

example

var key1 = "test1";
var key2 = "test2";

var table = { key1: true, key2: true };

But I would like the table to end up being 但我希望桌子最终成为现实

{ test1: true, test2: true }

You can use it by following example: 您可以通过以下示例使用它:

var key1 = "test1",
  key2 = "test2",
  table = {};

table[ key1 ] = true;
table[ key2 ] = true;

console.log( table ); // { test1: true, test2: true }

See jsFiddle demo . 请参阅jsFiddle 演示

So accessing them would be like 所以访问它们就像

console.log( table.test1 );

or 要么

console.log( table[ key1 ] );

or 要么

console.log( table[ "test1" ] );

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

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