簡體   English   中英

如何僅在Jquery / Javascript中尚不存在的字符串中添加字符串?

[英]how to add a string to an array only if it doesn't exist yet in Jquery/Javascript?

當用戶瀏覽我的應用程序時,我正在填充站點地圖數組。

但是,我填寫站點地圖的邏輯是有缺陷的。 這是我在做什么:

var siteMap = [],
    j = siteMap.length;

$(document).on( "pagebeforechange", function( e, data ) {

    if (j == 0 ){
        // add cause sitemap has no elements
        siteMap.push( { type: "external", data: data });
        } else {
            // loop through the sitemap object
            for ( var i = 0; i < j; i++) {
            // check if element is already stored
            if ( data.toPage == self.options.siteMap[i].data.toPage ){
                break;
                }   
            self.options.siteMap.push( { type: "external", data: data } );
            }           
        }
    }); 

問題是我的休息沒有按預期進行。 我想遍歷站點地圖,並將data.toPage (類似於/some/page.html之的字符串)與我已經存儲的內容進行比較。 如果找到匹配項,則循環應結束而無需將新元素推送到站點地圖。 但是,現在我正在循環,如果在循環postion(1)中找不到元素,則不會觸發該中斷,並且會在每個循環上添加一個條目,直到條目匹配為止。

問題
如何修復循環,因此僅在不存在匹配項的情況下才添加條目?

感謝幫助!

編輯
這就是我現在所擁有的:

(function( $, window) {
   $.widget("mobile.multiview",$.mobile.widget, {   
      options: {
         siteMap = {};
         },
      eventBindings: function() {

        $(document).on( "pagebeforechange", function( e, data ) {

            var self = this;
            if (!self.options.siteMap[data.toPage]){
               self.options.siteMap[data.toPage] = { type: "external", data: data };
               }
            });
        }
 }) (jQuery,this);

您在循環中對每次迭代執行測試。 在找到所需內容之前,它會在每次迭代中添加新條目。

您需要做的是查看元素是否已經在數組中, 然后添加(如果沒有)。 更好的是,首先放棄使用數組的想法,而僅將“ toPage”值用作對象屬性。

var sitemap = {};

$(document).on( "pagebeforechange", function( e, data ) {
  if (!sitemap[ data.toPage ])
    sitemap[data.toPage] = { type: "external", data: data };
});

暫無
暫無

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

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