创建 JavaScript 对象
2012-07-03
1302
我有这个函数
// add history paths and save data
function AddPath( strTag, strUserName, arrayLatLngPoints, pathColour) {
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
var date = new Date( parseInt( point.timestamp));
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour, date.toString());
date = null;
}
}
除了使用 addMarkers() 添加标记外,我还想将纬度、经度和时间戳存储在一个对象中。
我认为最好的存储方式是这样的
{ strUserName : { timestamp : point.timestamp , LatLng : point.LatLng }, strUserName : { timestamp : point.timestamp , LatLng : point.LatLng } }
或
{ strUserName : { timestamp : point.timestamp , LatLng : { lat : point.lat, lng : point.lng } }, ..
我如何创建这个对象?
更新:
感谢回复。 我尝试了以下方法。
// add history paths and save data
function AddPath( strTag, strUserName, arrayLatLngPoints, pathColour) {
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
var pos = new google.maps.LatLng(point.lat, point.lng);
var history = {
strUserName : {
timestamp : point.timestamp ,
LatLng : pos
}
};
var date = new Date( parseInt( point.timestamp));
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour, date.toString());
date = null;
}
console.log(history);
}
查看控制台的屏幕截图
用户名不起作用,我没有为每个时间戳获取一个项目,它只是覆盖了一个条目?
2个回答
How can i create this object?
和您做的非常相似:
var obj = { strUserName : { timestamp : point.timestamp , LatLng : point.LatLng }, strUserName : { timestamp : point.timestamp , LatLng : point.LatLng } };
或者更易读:
var obj = {
strUserName : {
timestamp : point.timestamp ,
LatLng : point.LatLng
},
strUserName : {
timestamp : point.timestamp ,
LatLng : point.LatLng
}
};
这是一个 对象初始化程序 。它使用给定的属性创建一个新对象(实际上是三个新对象),并返回对最外层对象的引用。
举一些更简单的例子:
// Create a blank object (an object with no properties of its own):
var a = {};
// Create an object with a `name` property with the value "Fred"
var b = {name: "Fred"};
// Create an object with a `foo` property, which is *another* freshly-created
// object with a `name` property with the value "Barney"
var c = {
foo: {
name: "Barney"
}
};
关于您更新的问题:
the username has not worked and im not getting an item for each timestamp, its just overwriting the one entry?
当然是,您在每个循环中覆盖了
history
,而没有将早期的副本存储在任何地方。例如,您可以将它们存储在数组中:
// add history paths and save data
function AddPath( strTag, strUserName, arrayLatLngPoints, pathColour) {
var historyArray = [];
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
var pos = new google.maps.LatLng(point.lat, point.lng);
historyArray[i] = {
strUserName : {
timestamp : point.timestamp ,
LatLng : pos
}
};
var date = new Date( parseInt( point.timestamp));
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour, date.toString());
date = null;
}
console.log(historyArray);
}
T.J. Crowder
2012-07-03
var obj = {strUserName: {timestamp: point.timestamp, lat: point.lat, long: point.long}}
Someth Victory
2012-07-03