[英]Javascript loop through array keys containing comma seperated values
I am trying to figure out the best way to split a object that has many key value pairs over 800 points ( they are X and Y coordinates) 我试图找出最好的方法来拆分一个对象,该对象具有超过800点的许多键值对(它们是X和Y坐标)
I would like to split X into its own array and Y into a separate array so that I can access X alone and Y alone. 我想将X拆分为自己的数组,将Y拆分为单独的数组,以便我可以单独访问X和单独访问Y。
Here is the structure of the points and what I have attempted 这是要点的结构以及我尝试过的
var path = {
0: [41, -73],
1: [41, -74],
2: [42, -75],
3: [43, -76]
};
for (var key in path) {
console.log("key " + key + " has value " + path[key]);
}
This will log 这将记录
key 0 has value 41,-73
key 1 has value 42,-74
key 2 has value 43,-75
key 3 has value 44,-76
I need the first value to be stored in its own array and the second value into another array. 我需要第一个值存储在其自己的数组中,第二个值存储在另一个数组中。
For example I would like to access all of X and Y as such, 例如,我想这样访问所有X和Y,
var x = [41, 42, 43, 44]
var y = [-73,-74,-75,-76]
JS FIDDLE HERE http://jsfiddle.net/b3j4w9bv/14/ JS FIDDLE HERE http://jsfiddle.net/b3j4w9bv/14/
Thanks! 谢谢!
You could do something along these lines: 您可以按照以下方式进行操作:
var path = {
0: [41, -73],
1: [41, -74],
2: [42, -75],
3: [43, -76]
};
var x_path = [];
var y_path = [];
for(var key in path)
{
//console.log("key " + key + " has value " + path[key]);
//create a split on , for x & y
var split_path = path[key];
//grab the value of the split:
var x = split_path[0];
var y = split_path[1];
//add the coords to their arrays.
x_path.push(x);
y_path.push(y);
//output result:
console.log(x_path);
console.log(y_path);
}
I haven't tested this in terms of perfomance..it might not be the most efficient 我还没有在性能方面进行测试..它可能不是最有效的
fiddle: http://jsfiddle.net/g123vyuv/ 小提琴: http : //jsfiddle.net/g123vyuv/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.