我們試圖用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
什麼是味精?它對於 –
這個問題很重要,你能告訴我們味精嗎? –