Invalid assignment left-hand side, javascript

前端 未结 6 1667
清酒与你
清酒与你 2021-01-15 16:33

I am sure I am doing something silly here:

var addhtml = \'
\' += \'
e[\"screen_name]&
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 16:44

    += means "take the thing on the left, add this to it, and store the result in the thing on the left". The left-hand side of your += is a literal (the first one is '

    ). You can't assign to literals.

    Put it another way, a += b basically means a = a + b. You can see how that doesn't work if a is a literal rather than a variable.

    You just want + there:

    var addhtml = '
    ' + '
    e["screen_name]
    ' + '
    ' + '
    e["description"]
    ' + '
    '; console.log(addhtml);

    To give you an idea of the difference between + and +=:

    var a, b;
    a = "foo";
    b = a + "bar";  // Doesn't modify `a`
    console.log(a); // "foo"
    console.log(b); // "foobar"
    

    vs.

    var a, b;
    a = "foo";
    b = a += "bar"; // Modifies `a` (assigning the result to `b` is unusual -- very -- but valid)
    console.log(a); // "foobar" - note it's changed
    console.log(b); // "foobar"
    

    Off-topic:

    I'd also recommend indenting the subsequent lines of the assignment statement, but that's just style:

    var addhtml = '
    ' + '
    e["screen_name]
    ' + '
    ' + '
    e["description"]
    ' + '
    '; console.log(addhtml);

提交回复
热议问题