Underscore.js`过滤器`不起作用

时间:2016-05-20 16:09:55

标签: javascript underscore.js

我有以下代码片段,用于从用户选择的列表中选择哪些郊区(省略不相关的代码):

var allSuburbsList = new Array([{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}]);

var a3burbs = _.filter(allSuburbsList, function(s) { return s.SuburbAreaID === 3; }); 
// 3 is a test value. All the test suburbs so far fall under area no. 3.

使用此过滤器,a3burbs以空数组[]形式出现。如果我作弊并制作过滤器:

var a3burbs = _.filter(allSuburbsList, function(s) { return true; }); 

然后a3bubrs出现allSuburbsList的精确副本,其中包含所有郊区。我能做错什么?我使用的是与Underscore.js主页上指示的语法相同的语法。

顺便说一下,我从viewmodel数组属性填充allSuburbsList的方式是否与此有关:

var allSuburbsList = new Array(@Html.Raw(JsonConvert.SerializeObject(Model.AllSuburbs)));

仅仅是为了兴趣,我的第一次尝试是下面的可怕代码,但它有效:

var a3burbs = [];
@{for (var i = 0; i < Model.AllSuburbs.Length; i++) {
    @:if (allSuburbsList[@i].SuburbAreaID === 3) {
        @:a3burbs.push(allSuburbsList[@i]);
    };
};

2 个答案:

答案 0 :(得分:4)

您正在创建一个新数组传入数组。

将其更改为

{{1}}

答案 1 :(得分:0)

使用new Array([{}]),您将在另一个数组中创建一个数组。只需在没有new Array()

的情况下实例化