2017-01-27 33 views
0

我試圖返回所有符合條件的數組,該數組的條件是 屬性gmarker[i].pricefirsthour等於2.我該如何實現?這下面就是示例:返回所有符合財產條件的數組

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

回答

1

gmarker[i].pricefirsthour = 2是不是條件,而是分配計算結果爲2(並因此總是truthy )。您需要=====,而不是=

或者,較短,較新的JS特點:

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

@ Rockafella - 小心箭功能,他們用的ECMAScript 2015年推出,可能不是你的關心(如任何所有的瀏覽器都支持版本如果IE),請參閱[* MDN支持矩陣*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)。 – RobG

1

使用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);

相關問題