如何将[X:X1,Y:Y1]的数组转换为数字数组,其中数字被存储在JavaScript中,例如[X1,Y1,X2,Y2 ....]?
我的数组看起来像:
const arr = [1,2,3,4,5,6]
我想将此数组转换为看起来像
const arr2 = [ {x: 1, y, 2}, {x:3, y:4}, {x:5, y:6}]
这样的东西:
let res: any = [];
const arr = [1,2,3,4,5,6]
for (let i = 0; i < arr.length / 2; i++) {
let next = 0
res.push({x : arr[i + next], y : arr[i+1+next]})
next += 2;
}
console.log(res);
但这并不能给我正确的结果。
I have an array which looks like:
const arr = [1,2,3,4,5,6]
I want to convert this array to look something like
const arr2 = [ {x: 1, y, 2}, {x:3, y:4}, {x:5, y:6}]
I have tried something like this:
let res: any = [];
const arr = [1,2,3,4,5,6]
for (let i = 0; i < arr.length / 2; i++) {
let next = 0
res.push({x : arr[i + next], y : arr[i+1+next]})
next += 2;
}
console.log(res);
But this doesnt give me the correct results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以获得一对切成薄片的阵列,并创建具有短手属性的新对象。
一个简单的循环的更好方法。
You could get pairs of sliced arrays and create new objects with short hand properties.
A better approach with a simple loop.
您可以用减少
You can do this with reduce
您可以加入数字,然后通过使用RegexP与函数
string.prototype.match
一起对坐标进行分组。You can join the numbers and then group the coordinates by using a Regexp along with the function
String.prototype.match
.您错误地计算了索引。
You got the index computation wrong.