$.each() index start number in jQuery

前端 未结 8 1896
慢半拍i
慢半拍i 2021-01-05 02:28

How do I start jQuery $.each() index from 1 instead of 0?

I am using .each function to populate select box. So here I want to populate options in the se

相关标签:
8条回答
  • 2021-01-05 02:46

    This is what I did:

    var start = index + 1;
    

    This just adds 1 to the current index.. then use that new variable instead of 'index'.

    0 讨论(0)
  • 2021-01-05 02:52

    var data = [42, 1337];
    $.each(data, function(i) {
      i++;
      console.log(i);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-01-05 02:55

    $.each

    So try

    $.each(obj, function(i, elem) {
        if (i === 0) return;
        // do stuff
    });
    

    Alternatively rewrite your code so its so indexes and data start at 0. JavaScript is interally 0 based rather then 1 based like Matlab and some other languages.

    0 讨论(0)
  • 2021-01-05 02:58

    Seeing the clarification points in the comments below, jQuery.each or some variation thereof isn't the right tool at all. Use a for loop, and add 1 to the index to output the value of the <option>.

    Use .prepend to insert an option as the first child of a select:

    for (var i = 0; i < 10; i++) {
        $('select').prepend('<option>' + (i + 1) + '</option>');
    }
    
    0 讨论(0)
  • 2021-01-05 02:59

    You can start at any given starting value by simply adding that number to the current loop-set index value.

    $.each(( index ) => {
    
        index += 1 //or any other starting value
    
        // your code
    });
    
    0 讨论(0)
  • 2021-01-05 03:01

    You can't. Why not just declare another variable at the first line of the function var myIndex = index + 1;?

    0 讨论(0)
提交回复
热议问题