我想使用_.where
下划线函数,但我似乎无法让它在一个对象数组上工作。我有以下json:
var Planets = [
{name:"maths", percComp: "2", preReq: "english"},
{name:"english", percComp: "20", preReq: "geog"},
{name:"german", percComp: "20", preReq: "english"},
{name:"history", percComp: "20", preReq: "german"},
{name:"irish", percComp: "20", preReq: "geog"},
{name:"geog", percComp: "20", preReq: ""},
{name:"french", percComp: "20", preReq: "spanish"},
{name:"spanish", percComp: "57", preReq: "french"}
];
然后我使用以下代码将每个代码添加到一个数组:
$(jQuery.parseJSON(JSON.stringify(Planets))).each(function(){
var planet = new Class.Planet(this, paper);
universe.push(planet);
});
我正在尝试使用下划线从列表中获取项目,如下所示:
var planets = _.where(universe, {name: "maths"});
但是我收到以下脚本错误:
Uncaught TypeError: Object function (a){return new j(a)} has no method 'where'
编辑您也可以使用类似的东西
var planets = _.filter(Planets, function(p){ return p.name === "maths"});
_.where
仅适用于1.4.0 http://underscorejs.org/#where
你必须使用Varon的建议与_.find
或者你可以简单地使用JS https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
示例:http://jsfiddle.net/4mxjb/2/
// returns an array with objects where their name
// property is equal to 'maths'
Planets.filter(function(obj){
return obj.name === 'maths'
});
用下划线来获得这个星球
var planet = _.find(Planets, function(p) {return p.name == 'maths'});
只是为了清除旧答案中的混乱:
_.find
输入:比较功能
返回第一个匹配元素;_.filter
输入:比较功能
返回所有匹配元素;_.where
输入:对象
返回所有匹配元素;_.findWhere
输入:对象
返回第一个匹配元素。var Planets = [
{name:"maths", percComp: "2", preReq: "english"},
{name:"english", percComp: "20", preReq: "geog"},
{name:"german", percComp: "20", preReq: "english"},
{name:"history", percComp: "20", preReq: "german"},
{name:"irish", percComp: "20", preReq: "geog"},
{name:"geog", percComp: "20", preReq: ""},
{name:"french", percComp: "20", preReq: "spanish"},
{name:"spanish", percComp: "57", preReq: "french"}
];
console.log('---FIND---\n', // Returns only ONE matching element
_.find(Planets, function(o){ return o.preReq === 'english'; })
);
console.log('---FILTER---\n', // Returns ALL matching elements
_.filter(Planets, function(o){ return o.preReq === 'english'; })
);
console.log('---WHERE---\n', // Returns ALL matching elements
_.where(Planets, {preReq: 'english'})
);
console.log('---FINDWHERE---\n', // Returns only ONE matching element
_.findWhere(Planets, {preReq: 'english'})
);
<script
src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js">
</script>