这个函数如何获取索引值呢?

How does this function obtain the index value?

我看了一个代码片段,这个匿名函数传递了 index 和 value 的值作为参数。这有什么用,因为我们根本没有手动调用该函数? (除了通过事件调用)。此外,这个索引值(随后在函数中使用)来自哪里?到底是谁在传递这些值,它们来自哪里?

var hideCode = function houdini()
{
    var numRand = getRandom(4);
    $(".guess_box").each(function(index, value) 
    { 
        if(numRand == index)
        {
            $(this).append("<span id='has_discount'></span>");
            return false;
        } 
    });
}

当你写:

$(".guess_box").each(function(index, value) 
    { $(".guess_box").each(function(index, value) 
        {
             //do something
        }

每个函数采用的索引参数是一个迭代器,它从索引 0 开始到 jquery 选择器选择的项目的长度 - 1。

参考 - http://api.jquery.com/jquery.each/

来自 jQuery's docs

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

这意味着在调用 $('.guess_box') 之后,.each(...) 从 0 开始迭代返回的数组,直到长度为 1。这与在返回的数组上调用 for 循环非常相似。

以下代码片段向您展示了使用 jQuery 的 .each() 函数与使用纯 Javascript 和 for 循环的类似迭代相比的迭代结果。

var showCode = function houdini() {
  // Prints the results of each iteration so you can see what happens.
  $(".guess_box").each(function(index, value) {
    console.log($(this).text());
  });
  // In pure JS you would do something like this, which is very similar.
  var boxes = document.getElementsByClassName('guess_box');
  for (var i = 0; i < boxes.length; i++)
    console.log(boxes.item(i));
}
$('#tester').click(function() {
  showCode();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="guess_box">test 1</div>
<div class="guess_box">test 2</div>
<div class="guess_box">test 3</div>
<div class="guess_box">test 4</div>
<button id="tester">click me</button>