用于存储数组的变量值

时间:2016-08-22 09:08:12

标签: javascript jquery

如何变量值来存储数组?

查看我的代码:



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




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

有没有机会将这样的变量转换成JS数组?

4 个答案:

答案 0 :(得分:3)

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



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




答案 1 :(得分: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]);

// ...




答案 2 :(得分:0)

您是否尝试将现有变量添加到数组中?如果是这样,你只是错过方括号:

var collection = [normal, user, student];

如果您希望元素包含字符串值,您可以这样做:

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

答案 3 :(得分:0)

while (temp1->getnext() != 0)
    temp1 = temp1->getnext();
相关问题