开发者

Create array from points

I need to format an array from a list of values.

Currently I have the following hard-coded points:

points = [
{x: 20, y: 112},
{x: 23, y: 101},
{x: 51, y: 89},
{x: 63, y: 89},
{x: 84, y: 129},
{x: 64, y: 153},
{x: 45, y: 151},
{x: 38, y: 140},
{x: 28, y: 150},
{x: 10, y: 144},
{x: 0, y: 130},
{x: 10, y: 114}
];

The resulting array is to be passed to a function.

I now need to pass another array to the same function but I cannot hard-coded them as above. Instead, I am using a JS framework to grab the points dynamically using, for example, $(#container).get('points');

How do I convert the new array so that it is formatted si开发者_开发百科milarly to the x: | y: structure as above?

points="20,112, 23,101, 51,89, 63,89, 84,129, 64,153, 45,151, 38,140, 28,150, 10,144, 0,130, 10,114"

I found the following in MooTools:

Array.each([1, 2, 3], function(number, index)
{
    alert('x:' + number + ', y: ' + index);
});

...but somehow that doesn't seem like the correct way to do this.

Can I get a little guidance please?


You can split [docs] the string and iterate over it, taking two values in each iteration:

var parts = points.split(',');
var pointsArray = [];

for(var i = 0, l = parts.length; i < l; i += 2) {
    pointsArray.push({x: +parts[i], y: +parts[i+1]});
}


You should actualy split it twice:

var points = "12,12, 1,2, 3,4"
var arr = points.split(', ');
for(var i = 0; i< arr.length; i++)
{
  var point = arr[i].split(',');
  document.write(point+ ' <br />' );
  arr[i] = {x:point[0], y:point[1]};
  document.write('   '+arr[i].x + ' ' + arr[i].y + ' <br/>');
}

Apart from that, just like the other comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜