[英]JavaScript fixed array or object length?
我需要一種僅在數組或對象內存儲兩個值並將其長度限制為兩個值的方法。 原因是我正在使用jQuery Vectormap計算兩個坐標x1 / y1和x2 / y2之間的距離和繪制線。
每當點擊區域/國家/地區時,就會加載相應的標記並將其添加到地圖中
map.addMarker(id ,{latLng: [val.lat, val.long], name:val.name}) ; ect///
現在,每當單擊一個標記時,我都應該能夠跟蹤兩個標記的選擇計數並將它們的坐標存儲在數組中,然后進行計算。
onMarkerClick:function(e, code){
var coordinates = map.markers[code].config.latLng;
// latitude = coordinates[0]
// longitude = coordinates[1]
}
因此,如果我要為每個單擊的標記使用myArray.push([coordinates[0],coordinates[1]])
,那么我最終將獲得無數的坐標,因此無法繪制線條。
有沒有一種方法可以將myArray長度設置為2,然后在我推入更多值時覆蓋現有值?
謝謝
如果您想了解它,可以創建執行此操作的自定義類。
function CappedArray(Size)
{
this.push = function(Value) {
if(this.length==Size)
{
this.shift();
}
CappedArray.prototype.push.call(this, Value);
}
}
CappedArray.prototype = new Array();
//How you use it
var SomeArray = new CappedArray(2);
SomeArray.push([coordinates[0],coordinates[1]]);
...
另外,如果您要強制這樣的事實,即只能在連續的插入對中關聯點:
function PairArray()
{
this.push = function(Value) {
if(this.length==2)
{
this.splice(0, 2);
}
PairArray.prototype.push.call(this, Value);
}
}
PairArray.prototype = new Array();
//How you use it
var SomeArray = new PairArray();
SomeArray.push([coordinates[0],coordinates[1]]);
您可以使用如下對象:
var coords =
{
"c1": [x1,y1],
"c2": [x2,y2]
}
然后在添加坐標時,您可以:
coords.c1 = coordinates[0];
coords.c2 = coordinates[1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.