我们试图用for循环创建一个json对象。结果应该是这样的:如何将元素插入到JSON格式的Javascript对象中
posJSON = [
{
"position": [msg[0].Longitude, msg[0].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
},
{
"position": [msg[1].Longitude, msg[1].Latitude],
"radius": 0.05,
"color": [255, 0, 0, 255]
}
]
如果我们只是用创建对象的代码^一切工作正常,但如果我们试图dinamically创建这样的对象:
for(i=0; i < Object.keys(msg).length; i++) {
posJSON.push({
"position": [msg[i].Longitude, msg[i].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
});
}
它赢得没有工作。我们显然使用了错误的语法,但我们无法理解错误在哪里。 先谢谢任何能回答我们问题的人。
这是函数的全码:
import React, {Component} from 'react';
import DeckGL, {PathLayer} from 'deck.gl';
import DeckGL, {ScatterplotLayer} from 'deck.gl';
import $ from 'jquery';
var tableJSONStringed = null;
var posJSON = [];
//Position tracker
window.setInterval(function(){
var request = $.ajax({
url: "https://nedo93.000webhostapp.com/phpgetcoords.php",
method: "POST",
dataType: "json"
});
request.done(function(msg) {
tableJSONStringed = JSON.stringify(msg, null, " ");
var count = Object.keys(msg).length;
//CYCLE
for(i=0; i < Object.keys(msg).length; i++) {
posJSON.push({
"position": [msg[i].Longitude, msg[i].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
});
/*posJSON = [
{
"position": [msg[0].Longitude, msg[0].Latitude],
"radius": 0.05,
"color": [255, 255, 0, 255]
},
{
"position": [msg[1].Longitude, msg[1].Latitude],
"radius": 0.05,
"color": [255, 0, 0, 255]
}
];*/
});
request.fail(function(jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
});
}, 5000);
export default class DeckGLOverlay extends Component {
static get defaultViewport() {
return {
longitude: 11.25,
latitude: 43.77,
zoom: 16,
maxZoom: 18,
pitch: 40, //viewport tilt
bearing: 0
};
}
_initialize(gl) {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}
//Add in const { }, new layers's ID
render() {
const {viewport, scatters, pos, icon, paths, trailLength, time} = this.props;
//Add another instance of a new layer here:
const layers = [
new ScatterplotLayer({
id: 'scatters',
data: scatters,
radiusScale: 100,
outline: false
}),
new ScatterplotLayer({
id: 'pos',
data: posJSON,
radiusScale: 100,
outline: false
}),
new PathLayer({
id: 'paths',
data: paths,
rounded: true,
getColor: paths => [255, 0, 0, 255],
getWidth: paths => 0.03,
widthScale: 100
})
];
return (
<DeckGL {...viewport} layers={layers} onWebGLInitialized={this._initialize} />
);
}
}
在这里它是运行的周期的控制台输出:Image
请解释一下你的“这不会是什么意思工作”。它有什么作用? javascript控制台是否提供错误? – Soviut
什么是味精?它对于 –
这个问题很重要,你能告诉我们味精吗? –