JavaScript-Übliche-Fehler
- Vorherige Seite JS-Best Practices
- Nächste Seite JS-Performance
Dieses Kapitel zeigt einige häufige JavaScript-Fehler.
den unerwarteten Gebrauch des Zuweisungsoperators
Wenn ein Programmierer if
Der unerwartete Gebrauch des Zuweisungsoperators in=
)statt dem Vergleichsoperator (====
),JavaScript-Programme können einige unerwartete Ergebnisse erzeugen.
Dieser if
Der Befehl gibt zurück false
Wie erwartet), weil x nicht 10 ist:
var x = 0; if (x == 10)
Dieser if
Der Befehl gibt zurück true
Vielleicht nicht wie erwartet), weil 10 true ist:
var x = 0; if (x = 10)
Dieser if
Der Befehl gibt zurück false
Vielleicht nicht wie erwartet), weil 0 false ist:
var x = 0; if (x = 0)
Die Zuweisung gibt immer den Wert der Zuweisung zurück.
Erwartung eines lockeren Vergleichs
In normalen Vergleichen ist der Datentyp nicht wichtig. Dies if
Der Befehl gibt zurück true
:
var x = 10; var y = "10"; if (x == y)
In strengen Vergleichen ist der Datentyp tatsächlich wichtig. Dies if
Der Befehl gibt zurück false
:
var x = 10; var y = "10"; if (x === y)
Ein häufiger Fehler ist, zu vergessen, in switch
Der Befehl verwendet strengere Vergleiche:
Dieser switch
Der Befehl zeigt eine Meldung an:
var x = 10; switch(x) { case 10: alert("Hello"); }
Dieser switch
Der Befehl zeigt keine Meldung an:
var x = 10; switch(x) { case "10": alert("Hello"); }
Verwirrende Addition und Kettenverbindung
AdditionzurNumerische.
Kettenverbindung (Concatenation)zurZeichenkette.
In JavaScript verwenden beide Operationen denselben +
Operatoren.
Daher führt die Addition von Zahlen als numerische Werte und als Zeichenkette zu verschiedenen Ergebnissen:
var x = 10 + 5; // Das Ergebnis in x ist 15 var x = 10 + "5"; // Das Ergebnis in x ist "105"
Wenn zwei Variablen addiert werden, ist es schwer, das Ergebnis vorherzusagen:
var x = 10; var y = 5; var z = x + y; // Das Ergebnis in z ist 15 var x = 10; var y = "5"; var z = x + y; // Das Ergebnis in z ist "105"
Verwirrende Fließkommazahlen
Die Zahlen in JavaScript werden alle als 64-Bit gespeichertFloating-point numbers (Floats).
All programming languages, including JavaScript, have difficulties handling floating-point values:
var x = 0.1; var y = 0.2; var z = x + y // The result in z will not be 0.3
To solve the above problem, please use multiplication and division operations:
Beispiel
var z = (x * 10 + y * 10) / 10; // The result in z will be 0.3
Line break in JavaScript strings
JavaScript allows you to split a statement into two lines:
Example 1
var x = "Hello World!";
But, it is incorrect to break lines in the middle of a string:
Example 2
var x = "Hello World!";
If you need to break lines in a string, you must use the backslash:
Example 3
var x = "Hello ", World!";
Misplaced semicolon
Because of a misplaced semicolon, this code block will always execute regardless of the value of x:
if (x == 19); { // code block }
Line break in return statements
Automatically closing statements at the end of a line is the default JavaScript behavior.
That's why the following two examples return the same result:
Example 1
function myFunction(a) { var power = 10 return a * power }
Example 2
function myFunction(a) { var power = 10; return a * power; }
JavaScript also allows you to split a statement into two lines.
That's why Example 3 will also return the same result:
Example 3
function myFunction(a) { var power = 10; return a * power; }
But, if you put return
What will happen if the statement is split into two lines:
Example 4
function myFunction(a) { var power = 10; return a * power; }
This function will return undefined
!
Why? Because JavaScript assumes that you mean:
Example 5
function myFunction(a) { var power = 10; return; a * power; }
Explanation
If a statement is incomplete:
var
JavaScript will complete this statement by reading the next line:
power = 10;
But because this statement is complete:
return
JavaScript will automatically close this statement:
return;
This happens because in JavaScript, using a semicolon to close (end) a statement is optional.
JavaScript closes at the end of the line return
statement, because it is a complete statement itself.
So, never do this return
The statement is for line break.
Access the array through named index
许多编程语言支持带有命名索引的数组。
带有命名索引的数组被称为关联数组(或散列)。
JavaScript 不支持带有命名索引的数组。
在 JavaScript 中,数组使用数字索引:
Beispiel
var person = []; person[0] = "Bill"; person[1] = "Gates"; person[2] = 46; var x = person.length; // person.length 将返回 3 var y = person[0]; // person[0] 将返回 "Bill"
在 JavaScript 中,对象使用命名索引.
如果您使用命名索引,那么在访问数组时,JavaScript 会将数组重新定义为标准对象。
在自动重定义之后,数组方法或属性将产生未定义或非正确的结果:
Beispiel
var person = []; person["firstName"] = "Bill"; person["lastName"] = "Gates"; person["age"] = 46; var x = person.length; // person.length 将返回 0 var y = person[0]; // person[0] 将返回 undefined
用逗号来结束定义
对象和数组定义中的尾随逗号在 ECMAScript 5 中是合法的。
对象实例:
person = {firstName:"Bill", lastName:"Gates", age:62,}
数组实例:
points = [35, 450, 2, 7, 30, 16,];
警告!!
Internet Explorer 8 会崩溃。
JSON 不允许尾随逗号。
JSON:
person = {firstName:"Bill", lastName:"Gates", age:62}
JSON:
points = [35, 450, 2, 7, 30, 16];
Undefined 不是 Null
JavaScript 对象、变量、属性和方法可以是未定义的。
此外,空的 JavaScript 对象的值可以为 null
.
这可能会使测试对象是否为空变得有点困难。
您可以通过测试类型是否为 undefined
,以测试对象是否存在:
Beispiel
if (typeof myObj === "undefined")
Sie können jedoch nicht testen, ob das Objekt null
, da ein Fehler ausgelöst wird, wenn das Objekt nicht definiert ist:
Falsch:
if (myObj === null)
Um dieses Problem zu lösen, muss getestet werden, ob das Objekt null
, anstatt undefined.
Dies wird jedoch immer noch einen Fehler verursachen:
Falsch:
if (myObj !== null && typeof myObj !== "undefined")
Daher muss vor dem Testen auf Nicht-null geprüft werden, ob es nicht definiert ist:
Korrekt:
if (typeof myObj !== "undefined" && myObj !== null)
keinen Block-Scope erwarten
JavaScript wirderzeugt für jeden Code-Block einen neuen Scope.
Viele Programmiersprachen sind so, aber JavaScript Das ist nicht der Fall.
dachte, dass dieser Code undefined
ist ein häufiger Fehler neuer JavaScript-Entwickler:
Beispiel
for (var i = 0; i < 10; i++) { // Code-Block } return i;
- Vorherige Seite JS-Best Practices
- Nächste Seite JS-Performance