简体   繁体   English

Javascript:为什么 % 运算符作用于字符串?

[英]Javascript : Why does % operator work on strings?

I am really baffled as to why the following code should work in Javascript:我真的很困惑为什么下面的代码应该在 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? Javascript 是否尝试将字符串转换为数字? (type promotion of sorts) (各种类型的提升)

PS I am from C++ background. PS我是C++背景。

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: % (和*/ )是MultiplicativeOperator s,当使用其中任何一个时,运算符的两边都会转换为数字:

  1. Let lnum be?让 lnum 成为? ToNumeric(leftValue). ToNumeric(左值)。
  2. Let rnum be?让 rnum 成为? ToNumeric(rightValue). ToNumeric(右值)。
  3. If Type(lnum) is different from Type(rnum), throw a TypeError exception.如果 Type(lnum) 与 Type(rnum) 不同,则抛出 TypeError 异常。
  4. Let T be Type(lnum).令 T 为 Type(lnum)。
  5. If MultiplicativeOperator is *, return T::multiply(lnum, rnum).如果 MultiplicativeOperator 是 *,则返回 T::multiply(lnum, rnum)。
  6. If MultiplicativeOperator is /, return T::divide(lnum, rnum).如果 MultiplicativeOperator 是 /,则返回 T::divide(lnum, rnum)。
  7. Else,别的,

    a.一种。 Assert: MultiplicativeOperator is %.断言:MultiplicativeOperator 是 %。

    b. b. Return T::remainder(lnum, rnum).返回 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 .它不会抛出错误,除非其中一个ToNumeric返回一个number ,而另一个ToNumeric返回一个bigint BigInts are the only type which require the explicit type casting you're expecting. BigInts 是唯一需要您期望的显式类型转换的类型。

Note that in Typescript, which is a (mostly) type-safe version of Javascript, this sort of thing does result in an error, specifically:请注意,在 Typescript 中,它是 Javascript 的(大部分)类型安全版本,这种情况确实会导致错误,具体而言:

The right-hand (or left-hand) side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.算术运算的右侧(或左侧)必须是“any”、“number”、“bigint”或枚举类型。 ts(2363) 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.但是标准 Javascript,在出现此类冲突类型问题的情况下,几乎总是倾向于尝试执行操作而不是抛出错误。 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.这没有多大意义,因为obj是 object(并且在大多数情况下不能非常有意义地+ d 带有字符串),但语言并不禁止它。

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.发生这种情况是因为当您尝试使用只有数字的字符串进行数学运算时,Javacript 会尝试将它们转换为数字以进行此操作。 It is called "Type coercion" More information can be founded inMDN它被称为“类型强制”更多信息可以在MDN中找到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果字符串在 Javascript 中是不可变的,为什么 += 运算符会以这种方式工作? - If strings are immutable in Javascript, why does the += operator work the way it does? 为什么|| 操作员不能在 JavaScript 中工作? - Why does the || operator not work in JavaScript? 为什么使用++的增量与javascript中的字符串一起使用? - Why does increment using ++ work with strings in javascript? Javascript:为什么前缀运算符只能与模数一起使用,而不能与后缀运算符一起使用? - Javascript: Why does prefix operator work with modulus but not postfix operator? JavaScript-为什么增量运算符会修改不可变的字符串? - JavaScript - Why does the increment operator modify immutable strings? Javascript:逗号运算符,var和作用域-为什么它按它的方式工作? - Javascript: Comma operator, var, and scope - why does it work the way it does? JavaScript中令人困惑的逗号运算符。 为什么以这种方式工作? - Confusing comma operator in JavaScript. Why does it work in such manner? 为什么“new Date()。toString()”在给定Javascript运算符优先级的情况下工作? - Why does “new Date().toString()” work given Javascript operator precedence? Javascript在字符串中找到字母对,为什么我的测试不起作用? - Javascript find letter pairs in strings, why does my test not work? OR运算符如何在此javascript中工作? - How does the OR operator work in this javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM