我正在尝试使用 underscore.js 过滤这个 javascript 对象,但我不知道为什么它不起作用,它的意思是找到任何包含“how”的问题值。
var questions = [
{question: "what is your name"},
{question: "How old are you"},
{question: "whats is your mothers name"},
{question: "where do work/or study"},
];
var match = _.filter(questions),function(words){ return words === "how"});
alert(match); // its mean to print out -> how old are you?
完整代码在这里(underscore.js 已经包含在内):http://jsfiddle.net/7cFbk/
最佳答案
- 您使用
.filter(questions)
关闭了函数调用。最后一个)
不应该存在。 - 过滤的工作原理是遍历数组并调用每个元素的函数。在这里,每个元素都是一个对象
{question: "..."}
,而不是一个字符串。 - 您检查是否相等,而您要检查问题字符串是否包含 某个字符串。您甚至希望它不区分大小写。
- 你不能警告对象。请改用控制台和
console.log
。
所以:http://jsfiddle.net/7cFbk/45/
var questions = [
{question: "what is your name"},
{question: "How old are you"},
{question: "whats is your mothers name"},
{question: "where do work/or study"},
];
var evens = _.filter(questions, function(obj) {
// `~` with `indexOf` means "contains"
// `toLowerCase` to discard case of question string
return ~obj.question.toLowerCase().indexOf("how");
});
console.log(evens);
关于javascript - 使用 underscore.js 过滤 js 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924976/