What do square brackets around an expression mean, e.g. `var x = a + [b]`?

后端 未结 7 1955
清酒与你
清酒与你 2020-12-04 12:00

We have received some JavaScript from an agency that looks wrong, but works.

For some reason they are adding square brackets ([, ]) around v

7条回答
  •  一个人的身影
    2020-12-04 12:25

    b = "bar" + ["foo"]
    

    This is syntactically correct, but indeed very, very, superfluous. This is how it works:

    ["foo"]
    

    JavaScript takes the string "foo" and converts it to an array with one element, "foo":

    "bar" + ["foo"]
    

    when + is used, and one of the operands is a string, "bar" in this case, JavaScript converts the second one to a string. Since operand two is an Array, the Array.toString method is called, which, by default, returns all elements joined by a comma. We have one element, and the result will be equal to this element, i.e., in this context "foo" is equivalent to ["foo"].

    If you redefine Array.toString you can see better what's going on:

    alert("bar" + ["foo"])
    Array.prototype.toString = function() { return "???"; }
    alert("bar" + ["foo"])
    

提交回复
热议问题