简体   繁体   English

如何知道哪个 arguments 在 javascript 的匿名函数中作为参数传递

[英]How to know which arguments are passed as parameters in anonymous functions in javascript

I am completely new to Javascript and I'm wondering how the anonymous functions know which arguments are being passed as parameters.我对 Javascript 完全陌生,我想知道匿名函数如何知道哪个 arguments 作为参数传递。 Let me explain my doubt with the help of code:让我在代码的帮助下解释我的疑问:

camelize = function camelize(str) {
      return str.replace(/\W+(.)/g, function(match, chr)
       {
            return chr.toUpperCase();
        });
    }

console.log(camelize("JavaScript Exercises"));
console.log(camelize("JavaScript exercises"));
console.log(camelize("JavaScriptExercises"));

This code is supposed to return a camelcase version of the input string.此代码应该返回输入字符串的驼峰式版本。 I understand that the regex finds non-word characters globally.我知道正则表达式会在全球范围内找到非单词字符。 But how does the function inside know what are "match" and "chr"?但是里面的function怎么知道什么是“match”和“chr”呢?

The replace function accepts a function as its second parameter which it then calls, passing the results of the regex as the parameters of your function. replace function 接受 function 作为其第二个参数,然后调用该参数,将正则表达式的结果作为 function 的参数传递。

Here's an example of how one could implement a similar pattern这是一个如何实现类似模式的示例

 function foo(str, func) { for(let i in str) { //for every character func(i, str[i]); // call func with the index and character } } foo("hello world", function(index, char) { console.log(index, char); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM