我正在尝试根据半径和 x,y 坐标制作一个圆。除了数组不是我使用的正确格式外,我已经完成了所有操作。 我得到:
[
"X_PROPS:40,Y_PROPS:0",
"X_PROPS:39.99390780625565,Y_PROPS:0.6980962574913405",
"X_PROPS:39.97563308076383,Y_PROPS:1.3959798681000388",
"X_PROPS:39.94518139018295,Y_PROPS:2.093438249717753"
]
但我需要:
[
{X_PROPS:40,Y_PROPS:0},
{X_PROPS:39.99390780625565,Y_PROPS:0.6980962574913405},
{X_PROPS:39.97563308076383,Y_PROPS:1.3959798681000388},
{X_PROPS:39.94518139018295,Y_PROPS:2.093438249717753}
]
我试过这个:
function spec(radius, steps, centerX, centerY){
var xValues = [centerX];
var yValues = [centerY];
var result = [];
for (var i = 0; i < steps; i++) {
xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
result.push('X_PROPS:'+ xValues[i]+','+'Y_PROPS:'+ yValues[i]);
}
return result;
}
console.log(spec(40,360,0,0))
最佳答案
此表达式 'X_PROPS:'+ xValues[i]+','+'Y_PROPS:'+ yValues[i]
创建一个字符串。而是创建一个对象字面量:
function spec(radius, steps, centerX, centerY) {
var result = [];
for (var i = 0; i < steps; i++) {
result.push({
X_PROPS: (centerX + radius * Math.cos(2 * Math.PI * i / steps)),
Y_PROPS: (centerY + radius * Math.sin(2 * Math.PI * i / steps))
});
}
return result;
}
console.log(spec(40, 360, 0, 0))
关于javascript - 如何将数组转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59164003/