【问题标题】:Return all arrays that meet property condition返回所有满足属性条件的数组
【发布时间】:2017-01-27 08:49:31
【问题描述】:

我正在尝试返回满足以下条件的所有数组 属性gmarker[i].pricefirsthour 等于2。我怎样才能做到这一点?以下只是示例:

for (var i = 0; i < gmarker.length; i++) {
    if (gmarker[i].pricefirsthour = 2) {
        console.log("is equal to 2");
    };
}

【问题讨论】:

    标签: javascript arrays properties return


    【解决方案1】:

    gmarker[i].pricefirsthour = 2 不是条件,而是评估为2 的赋值(因此始终为真)。你需要=====,而不是=

    或者,更短,具有更新的 JS 功能:

    gmarker.filter(x => x.pricefirsthour === 2)
    

    【讨论】:

    • @Rockafella — 小心箭头函数,它们是在 ECMAScript 2015 中引入的,可能并非您关心的所有浏览器都支持(例如 IE 的任何版本),请参阅MDN support matrix
    【解决方案2】:

    使用Array.prototype.filter

    gmarker = gmarker.filter(function(o){
       return o.pricefirsthour == 2;
    });
    

    var gmarker = [{pricefirsthour:2},{pricefirsthour:21},{pricefirsthour:2},{pricefirsthour:7},{pricefirsthour:5},{pricefirsthour:2}];
    gmarker = gmarker.filter(function(o){
       return o.pricefirsthour == 2;
    });
    console.log(gmarker);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多