Why js operator "+"?
phpcn_u1582
phpcn_u1582 2017-06-12 09:23:43
0
4
690

Why '11' can be converted into the number 11,
but the result of 1 '11' is '111' string?

phpcn_u1582
phpcn_u1582

reply all (4)
淡淡烟草味

Since this answer existed before ES6, this answer is taken from ES5.

+'11'

Answer source: ECMAScript5.1 11.4.6

One dollar+operation converts its operation value into a number. Don’t ask why, it is defined in the specification.

1 + '11'

Answer source: ECMAScript5.1 11.6.1

Steps of addition operation:

  1. Convert the left and right values to metatypes (such as strings and numbers) first; for example, Boolean will be converted to numbers, and objects will usually be converted to strings, etc.;

  2. Add it up

    1. If either the lvalue or rvalue converted value is a string, both values will be converted into strings for splicing operation;

    2. Otherwise, convert both the lvalue and rvalue into numbers, and then perform addition operations on the numbers; (For example, the Boolean conversion element type is not a string, but is still a Boolean, so when judging this branch here, the Boolean Convert to number 1 or 0)

  3. Return results.

    阿神

    javascriptis a weakly typed language, and that's for one reason. Furthermore, if+is put together with a number, it is considered a positive number. For example,var a = +11is equivalent tovar a = 11. In this way,+will only be used as the concatenation operator when concatenating strings. And+ '11'is not a concatenated string, because there is no concatenated string at all. Sojswill implicitly convert'11'to11.

    I am also a beginner ofjs. This is my understanding. If it is wrong, you are welcome to correct me.

      仅有的幸福

      +'11' -----> Unary operator

      The unary + operator converts its operand to Number type.

      1+'11' ----> addition operator

      If one of the operands is of string type, convert the other operand to a string and return the result of the concatenation of the two strings.

        漂亮男人

        The

        +of+'11'is the positive of the positive and negative, which is equivalent toNumber('11')

        1 + '11'is the addition of addition and subtraction, calling the internaltoPrimitivemethod for comparison. When one of the parties is a string, it will try to call the other party'stoStringmethod

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!