Loop from A to Z in jQuery

后端 未结 5 1400
星月不相逢
星月不相逢 2021-01-12 14:20

How can I loop from A to Z? I\'d like to populate a select menu with the letters of the alphabet, eg


                        
    
提交评论

  • 2021-01-12 14:41

    One-liner

    [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(v=>`<option>${v}</option>`).join('')
    
    0 讨论(0)
  • 2021-01-12 14:46

    Use char codes: JavaScript Char Codes

    for (var i = 65; i <= 90; i++) {
        $('#select_id_or_class').append('<option>' + String.fromCharCode(i) + '</option>');
    }
    
    0 讨论(0)
  • 2021-01-12 15:05

    You can avoid having numbers like 65 in your code if you just use charCodeAt() and fromCharCode().

    Print letters from a to z:

    for(let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
      $('#select_id_or_class').append(
        '<option>' + String.fromCharCode(i) + '</option>'
      );
    }
    

    Or:

    const aCharCode = 'a'.charCodeAt(0);
    
    for(let i = aCharCode; i <= (aCharCode + 26); i++) {
      $('#select_id_or_class').append(
        '<option>' + String.fromCharCode(i) + '</option>'
      );
    }
    

    If you want the uppercase characters, replace 'a'.charCodeAt(0) with 'A'.charCodeAt(0)

    0 讨论(0)
  • 2021-01-12 15:06

    This answer demonstrates the nice idea that you do not need a hardcoded string. In short:

    for (i = 65; i <= 90; i++) { arr[i-65] = String.fromCharCode(i).toLowerCase(); }

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