简体   繁体   中英

Javascript : Why does % operator work on strings?

I am really baffled as to why the following code should work in Javascript:

var string  = '1233'
console.log(typeof string) // prints string
console.log(string % 2) // prints 1

var result = string - 4
console.log(result) // prints 1229

Why are operators like % and - are allowed on strings? Does Javascript try to convert the string to the number? (type promotion of sorts)

PS I am from C++ background.

Because the specification says so . % (and * and / ) are MultiplicativeOperator s, and when any of those are used, both sides of the operator are converted to numbers:

  1. Let lnum be? ToNumeric(leftValue).
  2. Let rnum be? ToNumeric(rightValue).
  3. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  4. Let T be Type(lnum).
  5. If MultiplicativeOperator is *, return T::multiply(lnum, rnum).
  6. If MultiplicativeOperator is /, return T::divide(lnum, rnum).
  7. Else,

    a. Assert: MultiplicativeOperator is %.

    b. Return T::remainder(lnum, rnum).

The same sort of thing is happening when - is used on non-numbers - both sides are coerced to numbers first, after which the operation is performed. It doesn't throw an error, unless one of the ToNumeric s returns a number , and the other ToNumeric returns a bigint . BigInts are the only type which require the explicit type casting you're expecting.

Note that in Typescript, which is a (mostly) type-safe version of Javascript, this sort of thing does result in an error, specifically:

The right-hand (or left-hand) side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ts(2363)

But standard Javascript, in the case of conflicting type issues like these, almost always prefers to attempt to carry out the operation instead of throwing errors. For similar reasons, you can do

 const obj = {}; const someStr = 'foo' + obj; console.log(someStr);

Which doesn't make much sense, since obj is an object (and can't be very meaningfully + d with a string in most situations), but the language doesn't prohibit it.

It's happening because when you try to make mathematical operations with string where you have numbers only, Javacript is trying to convert them to number in order to make this operation. It is called "Type coercion" More information can be founded inMDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM