使用underscore.js过滤js对象

use*_*482 7 javascript filter

我试图使用underscore.js过滤这个javascript对象,但我不知道为什么它不起作用,它的意思是找到任何有"如何"的问题值.

  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?
Run Code Online (Sandbox Code Playgroud)

完整的代码在这里(underscore.js已经包含在内):http://jsfiddle.net/7cFbk/

pim*_*vdb 15

  1. 你关闭了函数调用.filter(questions).最后)不应该在那里.
  2. 过滤通过迭代数组并使用每个元素调用函数来工作.这里,每个元素都是一个对象{question: "..."},而不是一个字符串.
  3. 检查是否相等,而您要检查问题字符串是否包含某个字符串.你甚至希望它不区分大小写.
  4. 您无法提醒对象.使用控制台而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);
Run Code Online (Sandbox Code Playgroud)