Somenath Sinha
Somenath Sinha

Reputation: 1214

How does this function obtain the index value?

I went through a code snippet, and this anonymous function is passed the value of index and value as parameters. How is this useful, since we're not manually calling the function at all? (other than via event calls). Further, from where does this index value (which is subsequently used in the function) originate? Who exactly is passing this values, and where do they come from?

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;
        } 
    });
}

Upvotes: 1

Views: 99

Answers (2)

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

From 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.

What this means is that it after $('.guess_box') is called, the .each(...) iterates over the returned array starting from 0 until length-1. This works very similarly to calling a for-loop on the returned array.

The following snippet shows you the results of the iteration using jQuery's .each() function compared to a similar iteration using pure Javascript and a for-loop.

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>

Upvotes: 2

Araknid
Araknid

Reputation: 476

When you write:

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

The index argument taken by the function in each is an iterator which starts with index 0 to length - 1 of the item selected by jquery selector.

Refer - http://api.jquery.com/jquery.each/

Upvotes: 4

Related Questions