【问题标题】:Working of javascript inline functionsjavascript内联函数的工作
【发布时间】:2015-08-05 10:23:46
【问题描述】:

我无法理解 function(match, p1, p2) 的工作原理。

match参数有什么用?如果我不写匹配参数,代码就会中断。

function incrementString(input) {
    if (isNaN(parseInt(input[input.length - 1]))) return input + '1';
    return input.replace(/(0*)([0-9]+$)/, function(match, p1, p2) {
        var up = parseInt(p2) + 1;
        return up.toString().length > p2.length ? p1.slice(0, -1) + up : p1 + up;
    });
}

P.S:我是完全使用 Js 进行开发的新手。然而,从过去几年开始,我一直在研究 JSF 和 Java。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    来自MDN

    str.replace(regexp|substr, newSubStr|function[, flags])
    

    在这种情况下,我们可以看到两个参数被传递给replace,一个正则表达式文字和一个函数表达式。那就是:

    str.replace(regexp, function)
    

    MDN 告诉我们它们是什么:

    函数(替换)
    要调用的函数以创建新的 子字符串(代替从参数接收的子字符串 1)。提供给此函数的参数在下面的“将函数指定为参数”部分中进行了描述。

    函数的参数如下:

    等等。等等。我不会引用整个表格。

    如果您将match 参数排除在参数列表之外,则分配给p1p2 的值将是第一个和第二个参数,而不是第二个和第三个参数。这些不是您需要的值。

    这就像拿这个代码:

    function call_with_one_two_three(f) {
        f(1,2,3);
    }
    
    call_with_one_two_three(function (one, two, three) {
        alert(two + three);
    });
    

    并决定由于您没有使用one,因此您不需要它:

    function call_with_one_two_three(f) {
        f(1,2,3);
    }
    
    call_with_one_two_three(function (two, three) {
        alert(two + three);
    });
    

    那给你two + three3

    简而言之:论点的位置很重要(而名称不重要)。

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多