从Array中分离和追加值

时间:2015-04-21 19:31:13

标签: javascript jquery arrays

我有一个这样的数组:["demo", "4532t78"]

它来自两个步骤:

var userInfo = $.parseJSON(JSONallUserInfo);
console.log(userInfo.available_client_ids); // gives me `["demo", "4532t78"]`

如何进一步分离这个数组,以便我可以将每个值附加到select?

4 个答案:

答案 0 :(得分:2)

听起来你有一个JSON字符串,如下所示:

{
    available_client_ids: ["demo", "4532t78"]
}

现在您直接记录包含数组的available_client_ids属性。您可以做的一件事就是将该属性分配给变量:

var clientIds = userInfo.available_client_ids;

然后你可以迭代它,因为它只是一个数组:

// Using Array.prototype.forEach
clientIds.forEach(function(id) {
    // do something with the id here, for example append to another string
    console.log(id);
});

您还可以查看使用数组方法mapreduce(或像Underscore.js这样的函数库中的等价物)直接从数组构建字符串。

此外,由于听起来你正在使用jQuery来处理其他东西,因此使用$ .parseJSON是有意义的,但是你应该知道在现代浏览器中有解析和序列化字符串和对象的内置JSON方法,以防万一你需要使用JSON但没有jQuery可用。

答案 1 :(得分:1)

可以使用索引访问数组中的元素,从0开始。

var myArray = ['zero', 'one', 'two', 'three'];

var firstElement = myArray[0];

firstElement将是字符串'zero'

一些阅读材料:

完整文档here

答案 2 :(得分:1)

您可以使用Array.prototype.forEach()遍历每个元素并将其附加到<select>

var userInfo = ["demo", "4532t78"], 
    dropdown1 = document.getElementById('dropdown1');

userInfo.forEach(function(el) {   
  var option = document.createElement('option'); 
  option.textContent = el; 
  dropdown1.appendChild(option);  
}); 
<select id="dropdown1">
</select>

答案 3 :(得分:0)

可以通过下标访问数组元素。因此,userInfo.available_client_ids[0]将评估为"demo",而userInfo.available_client_ids[1]将评估为"4532t78"。然后,您可以使用这些表达式来创建select元素。它也可以作为一个循环来完成,你可以将索引从0改为但不包括userInfo.available_client_ids.length

for (var i = 0; i < userInfo.available_client_ids.length; ++i) {
    console.log(userInfo.available_client_ids[i]);
}
相关问题