SyntaxError: Unexpected EOF in JS

前端 未结 1 2014
北海茫月
北海茫月 2021-01-22 09:58

I have the following script:

function getMoods(nb) {
    var index;
    var a = [\"Banana\", \"Coconut\", \"Peach\", \"Apple\", ...];
    for (index=0; index<         


        
相关标签:
1条回答
  • 2021-01-22 10:33

    There are two problems:

    1. A wrong use of the spread operator ...:

      ["Banana", "Coconut", "Peach", "Apple", ...];
      

      This throws SyntaxError: expected expression, got ']', because after the spread operator there isn't any iterable object.

    2. JavaScript doesn't support multiline strings.

      You can use some alternatives:

      • Concatenate multiple strings

        moods += 
          '<div class="checkbox">'
            +'<label for="'+a[index]+'">'
              +'<input type="checkbox" id="'+a[index]+'" class="moods"> '+a[index]
            +'</label>'
          +'</div>';
        
      • Use \ at the end of each line to continue the string at the next one

        moods += '\
          <div class="checkbox">\
            <label for="'+a[index]+'">\
              <input type="checkbox" id="'+a[index]+'" class="moods"> '+a[index]+'\
            </label>\
          </div>';
        
      • Join an array of strings:

        moods += [
          '<div class="checkbox">',
            '<label for="'+a[index]+'">',
              '<input type="checkbox" id="'+a[index]+'" class="moods"> '+a[index],
            '</label>',
          '</div>'].join('');
        
    0 讨论(0)
提交回复
热议问题