JS中的文本函数第一个参数(_)

Text function first param (_) in JS

本文关键字:参数 第一个 函数 文本 JS      更新时间:2023-09-26
<p class="myString">something to remove xxx here within a tag</p>
$('p.myString').text(function(_, txt) {
    return txt.replace('xxx', '');
});

上面的代码有效,但第一个参数是做什么的? _

正如文档所述,第一个参数是您当前正在处理的元素的索引。

名为 _ 的参数通常表示此参数将被忽略,并且不会在函数中使用。这只是一个约定,它仍然是一个有效的参数名称,没有什么可以阻止您使用此参数。

如果使用参数,参数的确切用途取决于框架 - 在这种情况下,jQuery文本函数如另一个答案中所述。

在你的代码段中,_位于index的位置,它位于.text(fn)函数中的第一个参数,第二个是集合中的元素:

$('p.myString').text(function(_, txt) {
    return txt.replace('xxx', _); // it changes all the "xxx" with their index values
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>
<p class="myString">something to remove xxx here within a tag</p>

您可以看到_表示元素的索引,因为_they相对于其parent_显示。