Javascript循环包含逗号分隔值的数组键

时间:2014-10-23 03:19:42

标签: javascript arrays html5 object coordinates

我试图找出分割具有超过800个点的许多键值对的对象的最佳方法(它们是X和Y坐标)

我想将X分成它自己的数组,将Y分成一个单独的数组,这样我就可以单独访问X而单独使用Y.

这是积分的结构和我尝试的内容

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]);
}

这将记录

  key 0 has value 41,-73 

  key 1 has value 42,-74 

  key 2 has value 43,-75 

  key 3 has value 44,-76

我需要将第一个值存储在自己的数组中,将第二个值存储到另一个数组中。

例如,我想访问所有的X和Y,

var x = [41, 42, 43, 44]
var y = [-73,-74,-75,-76]

JS FIDDLE HERE http://jsfiddle.net/b3j4w9bv/14/

谢谢!

1 个答案:

答案 0 :(得分:2)

你可以沿着这些方向做点什么:

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);
}

我没有在性能方面对此进行测试..这可能不是最有效的

小提琴:http://jsfiddle.net/g123vyuv/