2016-08-22 81 views
-1

如何将变量值存储到数组中?用于存储数组的变量值

看看我的代码:

var collection =normal,user,student ; 
 
var array = [collection]; 
 
alert(array[0]);

在这种情况下,警报会弹出一个正常的用户,学生。但我需要一个数组,如数组[0]得到正常,数组[1]得到用户,数组[2]得到这样的学生 怎么可能

是否有任何机会转换成JS数组?

+0

是'正常的,用户,学生变量? – Satpal

+0

没有它的值.. –

+0

@SHERINAS:单个字符串? –

回答

0
var collection = "normal,user,student"; 
var jsarray = collection.split(","); 
alert(jsarray[0]); 
alert(jsarray[1]); 
alert(jsarray[2]); 
3

由于normal,user,student是值。您可以使用split(),作为分隔符来拆分字符串,然后可以使用索引来访问元素。

var collection = "normal,user,student"; 
 
var array = collection.split(','); 
 
console.log(array[0]);

+0

tanq ........... –

2

有很多很多的方法来创建阵列......一些例子:

// just declare an array directly 
 
var array1 = ["normal", "user", "student"]; 
 
console.log(array1[0]); 
 

 
// use split to create an array out of a string 
 
var collection = "normal,user,student"; 
 
var array2 = collection.split(","); 
 
console.log(array2[1]); 
 

 
// use split and map to create an array by your needs 
 
var collection = " normal, user , student "; 
 
var array3 = collection.split(",").map(function(value) { 
 
    return value.trim(); 
 
}); 
 
console.log(array3[2]); 
 

 
// push each value to the array 
 
var array4 = []; 
 
array4.push("normal"); 
 
array4.push("user"); 
 
array4.push("student"); 
 
console.log(array4[0]); 
 

 
// ...

+0

tanq ........... –

+0

你是什么意思? @SHERINAS – eisbehr

+0

哈哈谢谢:P –

0

你们是不是要在现有的变量添加到数组?如果是的话你只是缺少你方括号:

var collection = [normal, user, student]; 

如果你想包含字符串值的元素,你会做这样的:

var collection = ["normal", "user", "student"];