如何在Javascript .filter()方法中将额外参数传递给回调函数? [英] How do I pass an extra parameter to the callback function in Javascript .filter() method?

查看:410
本文介绍了如何在Javascript .filter()方法中将额外参数传递给回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Array中的每个字符串与给定的字符串进行比较。我目前的实现是:

I want to compare each string in an Array with a given string. My current implementation is:

function startsWith(element) {
    return element.indexOf(wordToCompare) === 0;
}
addressBook.filter(startsWith);

这个简单的功能有效,但只是因为现在正在设置 wordToCompare 作为一个全局变量,但我当然希望避免这种情况并将其作为参数传递。我的问题是我不知道如何定义 startsWith()因此它接受一个额外的参数,因为我真的不明白它所采用的默认参数是如何传递的。我已经尝试了所有我能想到的不同方法,但没有一种方法可以工作。

This simple function works, but only because right now wordToCompare is being set as a global variable, but of course I want to avoid this and pass it as a parameter. My problem is that I am not sure how to define startsWith() so it accepts one extra parameter, because I dont really understand how the default parameters it takes are passed. I've tried all the different ways I can think of and none of them work.

如果你还可以解释传递参数如何内置回调函数(对不起,我不知道这些更好的术语)工作会很棒

If you could also explain how the passed parameters to 'built in' callback functions (sorry, I dont know of a better term for these) work that would be great

推荐答案

制作 startsWith 接受要比较的单词和返回一个函数,然后将其用作过滤/回调函数:

Make startsWith accept the word to compare against and return a function which will then be used as filter/callback function:

function startsWith(wordToCompare) {
    return function(element) {
        return element.indexOf(wordToCompare) === 0;
    }
}

addressBook.filter(startsWith(wordToCompare));

另一种选择是使用 Function.prototype.bind [MDN] (仅在支持ECMAScript 5的浏览器中可用,请按照旧版浏览器的垫片链接)并修复第一个参数:

Another option would be to use Function.prototype.bind [MDN] (only available in browser supporting ECMAScript 5, follow a link for a shim for older browsers) and "fix" the first argument:

function startsWith(wordToCompare, element) {
    return element.indexOf(wordToCompare) === 0;
}

addressBook.filter(startsWith.bind(this, wordToCompare));








我真的不是了解如何传递默认参数

I dont really understand how the default parameters it takes are passed

没有什么特别之处。在某些时候, filter 只是调用回调并传递数组的当前元素。所以它是一个调用另一个函数的函数,在这种情况下是你作为参数传递的回调。

There is nothing special about it. At some point, filter just calls the callback and passes the current element of the array. So it's a function calling another function, in this case the callback you pass as argument.

这是一个类似函数的例子:

Here is an example of a similar function:

function filter(array, callback) {
    var result = [];
    for(var i = 0, l = array.length; i < l; i++) {
        if(callback(array[i])) {  // here callback is called with the current element
            result.push(array[i]);
        }
    }
    return result;
}

这篇关于如何在Javascript .filter()方法中将额外参数传递给回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆