簡體   English   中英

比較JavaScript對象數組中對象的屬性

[英]compare property of object within object array in JavaScript

渲染HTML時,我想檢查Handlebars循環中當前對象的isActive屬性是true還是false。 因此,我的對象數組訪問了給定的url參數,並且屬性必須自行檢查布爾值。

module.exports = (url) => {
  return {
    menu: [{
      href: '/1.1',
      isActive: function() {
        return this.href == url;
      }
    }, {
      href: '/1.2',
      isActive: function() {
        return this.href == url;
      }
    }, {
      href: '/1.3',
      isActive: function() {
        return this.href == url;
      }
    }]
  }
};

如您所見,我總是必須設置一個比較函數。 我試圖創建一個功能

const isActiveLink = (obj) => {
   return obj.href == url;
}

然后在我的菜單中

isActive: isActiveLink(this);

但是執行此操作時,該對象未定義。 有沒有一種方法可以使基於給定參數的isActive動態更干凈?

創建簡單的JS對象時,不能使用this對象。 您可能想更詳細地研究this工作方式。 可能會造成混亂。

一種您想要做的方法是創建一個像這樣的類:

class MenuItem {
    constructor(href, url) {
        this.href = href
        this.url = url
    }

    isActive() {
        return this.href == this.url;
    }
}

然后,您可以像這樣進行導出:

module.exports = (url) => {
    return {
        menu: [
            new MenuItem('/1.1', url),
            new MenuItem('/1.2', url),
            new MenuItem('/1.3', url)
        ]
    }
};

暫無
暫無

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

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