嗨,我有一组由php检索并显示在两个隐藏文本字段上的单词,如下所示:
标题:
Red Apple, Grapes, Green Apple, Orange文件名:
red_apple5, grapes1, green_apple2, orange3我是否可以将其转换为对象或数组,如下所示:
T = {"Red Apple" , "Grapes" , "Green Apple" , "Orange"}
S = {"red_apple5" , "grapes1" , "green_apple2" , "orange3"}我想把他们每个都加到一个名单上。有办法这样做吗?
发布于 2012-07-05 23:07:54
假设您想要创建一个有效的对象,请使用下面的代码作为参考。注:为说明目的作了一些修改。
<div id="output"></div>jQuery
var titles = 'Red Apple, Grapes, Green Apple, Orange'.split(', ');
var fileNames = 'red_apple5, grapes1, green_apple2, orange3'.split(', ');
var newObject = {};
for(var i=0; i < titles.length; i++){
newObject [titles[i]] = fileNames[i];
}
$('#output').text(JSON.stringify(newObject));演示:http://jsfiddle.net/GHgsT/
上面的代码循环遍历titles数组,然后将titles[index]值映射为对象的属性(键),将相应的fileNames[index]值映射为属性值。
发布于 2012-07-05 22:55:41
var array = 'Red Apple, Grapes, Green Apple, Orange'.split(', ');发布于 2012-07-05 22:56:56
您可以使用javascript的拆分()方法来拆分字符串:
var str = "Red Apple, Grapes, Green Apple, Orange";
var arr = str.split(', ');
console.log(arr)要将它们附加到列表中,必须使用forEach()遍历新创建的数组,然后为每个项创建一个新的li。然后,可以将li作为子元素附加到ul中。
var list = document.getElementById("#IdOfYourList")
arr.forEach(function(a) {
var newLi = document.createElement("li")
newLi.innerHTML = a;
list.appendChild(newLi);
});还请注意,IE < 8不支持forEach,但可以在这里实现为数组原型:对象/数组/forEach
参考资料:对象/字符串/拆分
https://stackoverflow.com/questions/11353604
复制相似问题