[英]ES6: transfer nested array into array with objects using destructuring
我正在学习ES6 Destructuring并尝试找出将具有2个数字作为元素(例如x和y坐标)的嵌套数组转换为仅使用解构的对象数组的不同方法。
const points = [
[4, 5],
[3, 12],
[9, 30]
]
// goal: transfer to this format:
// [
// {},
// {},
// {}
// ]
一个(可能)最好的解决方案:
points.map(([ x, y ]) => {
return { x, y };
});
另一种尝试:
points.map(pair => {
const x = pair[0],
const y = pair[1]
});
// Uncaught SyntaxError: Unexpected token const
为什么我在这里得到一个SyntaxError?
附:
points.map(pair => {
const [ x, y ] = pair;
});
我得到一个包含3个未定义元素的数组。 为什么?
在一行中,返回是自动的。
一:
points.map(([ x, y ]) => ({ x, y }));
二:
points.map(pair => ({x: pair[0], y: pair[1]}));
或者多行:
points.map(pair => {
const x = pair[0];
const y = pair[1];
return {x, y};
});
三:
points.map(pair => {
const [ x, y ] = pair;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.