Subtraktion (-)
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Der Subtraktionsoperator (-
) subtrahiert die beiden Operanden und erzeugt deren Differenz.
Probieren Sie es aus
console.log(5 - 3);
// Expected output: 2
console.log(3.5 - 5);
// Expected output: -1.5
console.log(5 - "hello");
// Expected output: NaN
console.log(5 - true);
// Expected output: 4
Syntax
x - y
Beschreibung
Der -
Operator ist für zwei Arten von Operanden überladen: Zahl und BigInt. Er zwingt zuerst beide Operanden zu numerischen Werten und testet deren Typen. Er führt eine BigInt-Subtraktion durch, wenn beide Operanden BigInts werden; andernfalls führt er eine Zahlensubtraktion durch. Ein TypeError
wird ausgelöst, wenn ein Operand zu einem BigInt wird, der andere jedoch eine Zahl bleibt.
Beispiele
Subtraktion mit Zahlen
5 - 3; // 2
3 - 5; // -2
Andere Nicht-BigInt-Werte werden in Zahlen umgewandelt:
"foo" - 3; // NaN; "foo" is converted to the number NaN
5 - "3"; // 2; "3" is converted to the number 3
Subtraktion mit BigInts
2n - 1n; // 1n
Sie können BigInt- und Zahlenoperanden in der Subtraktion nicht mischen.
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
Um eine Subtraktion mit einem BigInt und einem Nicht-BigInt durchzuführen, konvertieren Sie einen der Operanden:
2n - BigInt(1); // 1n
Number(2n) - 1; // 1
Spezifikationen
Specification |
---|
ECMAScript® 2025 Language Specification # sec-subtraction-operator-minus |
Browser-Kompatibilität
BCD tables only load in the browser