将 json 数组转换为 javascript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5618548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert json array to javascript array
提问by shasi kanth
i have a json array that i want to convert into a plain javascript array:
我有一个 json 数组,我想将它转换为一个普通的 javascript 数组:
This is my json array:
这是我的 json 数组:
var users = {"0":"John","1":"Simon","2":"Randy"}
How to convert it into a plain javascript array like this:
如何将其转换为一个普通的 javascript 数组,如下所示:
var users = ["John", "Simon", "Randy"]
回答by Felix Kling
users
is already a JS object (not JSON). But here you go:
users
已经是一个 JS 对象(不是 JSON)。但是你去吧:
var users_array = [];
for(var i in users) {
if(users.hasOwnProperty(i) && !isNaN(+i)) {
users_array[+i] = users[i];
}
}
Edit:Insert elements at correct position in array. Thanks @RoToRa.
编辑:在数组中的正确位置插入元素。谢谢@RoToRa。
Maybe it is easier to not create this kind of object in the first place. How is it created?
也许一开始不创建这种对象更容易。它是如何创建的?
回答by David Tang
Just for fun - if you know the length of the array, then the following will work (and seems to be faster):
只是为了好玩 - 如果您知道数组的长度,那么以下将起作用(并且似乎更快):
users.length = 3;
users = Array.prototype.slice.call(users);
回答by shasi kanth
Well, here is a Jquery+Javascript solution, for those who are interested:
好吧,这里有一个 Jquery+Javascript 解决方案,供有兴趣的人使用:
var user_list = [];
$.each( users, function( key, value ) {
user_list.push( value );
});
console.log(user_list);