2016-12-04 90 views
0

我正在在node.js的一個程序(JavaScript的),我想它來與在一個變量名稱的數組,因此,像這樣添加陣列是在名稱的變量

const name = "test" 
const name = ["Contents", "Here"]; // Trying to make an array called the name 
// stored in the "name" variable 

謝謝!

+0

所以,在上面的例子中,你想創建一個名爲'test'的'const'? –

+0

'global [name] = [「Contents」,「Here」];'? –

+0

@JaromandaX是的,但ick! –

回答

1

您可以使用對象中的屬性名稱做到這一點。但是,AFAIK,你需要像eval()這樣的數組來完成它(並且你不應該使用eval())。

下面是它如何與一個對象去:

var myObject = {}; 
 
const name = "test" 
 
myObject[name] = ["Contents", "Here"]; 
 

 
// Test 
 
console.log(myObject.test); 
 
console.log(myObject[name]); 
 
console.log("Does object have a 'test' property? " + (name in myObject && name === "test"));

+0

爲什麼不讓'myObject'也是const? – melpomene

+0

@melpomene只是一個使用OP代碼的簡單例子。不會真的影響答案。 –

+0

@ melpomene-爲什麼使* name * a * const *成爲可能? – RobG

-1
const var_name = "test" 
const arr_name.push(var_name); 
console.log(arr_name)? 

我不確信此代碼將滿足您的需求。