簡體   English   中英

如何存儲對象數組?

[英]How do I store an array of objects?

我有一個對象image我可以做像image.top這樣的東西,它會返回一個值,或者我可以做image.myPoints[0].left ,它會返回一個值。 我基本上有這個圖像對象為我存儲值。 我希望能夠將多個image對象放在一個數組中,這樣我就可以這樣做:

$("#toPinpoint").mapImage({
                useAjax: false,
                pinpoints: [ { "top": 50,
                           "left": 280,
                           "width": 200,
                           "height": 200},
                         { "top": 0,
                           "left": 0,
                           "width": 300,
                           "height": 74 } ] 
            });

我使用此函數創建對象,將針點添加到對象上。 當調用mapImage函數時,會發生以下情況:

    $.fn.mapImage = function(options){



    //Set user input options and defaults
    var optionConfig = $.extend({}, $.fn.mapImage.defaults, options);

    image=this;
    this.image = this;

    // Assign defaults
    this.previewMode = optionConfig.previewMode;
    this.pinpoints = optionConfig.pinpoints;
    image.pinpoints = optionConfig.pinpoints;
    image.pinpointCount = 0;
    image.selected = 0;
    ...}

這將設置圖像屬性,現在我想用我的應用程序修改特性,然后將這些image對象保存到數組中。

我的問題是數組正在加載圖像對象,但它似乎用我剛剛推入的對象填充整個數組,因此它不會保存我的舊圖像對象。 例如,如果我執行myArray[0].myPoints[0].left ,讓我們說它重新打造30,然后我推送另一個myPoints [0] .left等於20的圖像對象,這是我的第一個圖像對象數組變成20而不是保存為30.如果這是一個解決這個問題的好方法,我將不勝感激。 謝謝!

使用array.push(x)應該將x添加到array的末尾。 但是,它不會創建x的副本,因此如果您再更改x的屬性並再次push()它,您的數組將包含兩個帶有更新屬性的x實例 - 我懷疑這就是您所看到的。 (也就是說,您可能正在更改imagetop屬性並再次push() ,而不是創建一個全新的image push() )。

var myArray = new Array();

您需要使用“new”關鍵字。

我認為你讓這比需要的更復雜。

(function($){
  $.fn.mapImage = function(options) {
    var defaults = { /* your defaults here */ };

    // Merge default options with passed in options and store
    options = ($.extend({}, defaults, options));

    // Do other stuff
  };
})(jQuery);

// Backup current pinpoints and modify the current one
$('#toPinpoints').data('pinpoints-backup', $('#toPinpoints').data('pinpoints').splice());
$('#toPinpoints').data('pinpoints')[0].top = 100;

// Push a new array of pinpoints
$('#toPinpoints').data('pinpoints').push({"top": 100, "left": 50, "width": 200, "height": 150});

小心jQuery.extend()因為它不會遞歸操作,因此默認子數組中的任何數組都將被options數組中的那些完全覆蓋, 而不是合並。

如果您稍后需要訪問精確定位數據,您可能希望通過執行類似this.data($.extend({}, $.fn.mapImage.defaults, options));類的操作來使用jQuery.data() this.data($.extend({}, $.fn.mapImage.defaults, options)); 而不是重新分配選項變量。 然后可以通過$('#toPinpoint').data('pinpoints')在任何地方訪問給定元素$('#toPinpoint').data('pinpoints') ,它將返回通過選項傳遞給mapImage()的相同數組。 然后,您可以使用jQuery.each()遍歷所有精確定位點。

如果我錯過了你想要做的事情,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM