Home >Web Front-end >JS Tutorial >How each browser handles extra commas when defining an object or array literal in js (json)_javascript skills
1. The js engine performs syntax analysis when the code is loaded. If the js written is not standardized, the syntax analysis will fail. The error at this time is called a syntax error
2. The syntax analysis is passed, and the js engine will execute the code. Errors that occur during execution are called runtime errors
Different engines handle these two errors differently. As follows:
In JSON format, the comma is the separator between multiple attribute key-value pairs, for example:
var json = { id: 1, name: 'heero' };
But when programming, it’s easy to add superfluous information. A comma is also added after the last key-value pair :
var json = { id: 1, name: 'heero', };
In this case, IE6 and 7 will report an error, but IE8 and other browsers will have no problem.
In an array, a comma is the separator between elements, for example:
var arr = [1, 2, 3];
Similarly, we may accidentally add a comma after the last element :
var arr = [1, 2, 3,];
Intuitively, this should be incorrect syntax. But in fact, all browsers are compatible with this situation, including IE6. Consider this sample code:
var arr = [1, 2, 3,];<code>var arr = [1, 2, 3,];<br>for (var i = 0; i < arr.length; i ) { alert(arr[i]); }
for (var i = 0; i < arr.length; i ) { alert(arr[i]); }
On browsers other than IE, 1, 2, and 3 are output in sequence; but on IE browser, 1, 2, 3, and undefined are output in sequence. Obviously, IE adds an undefined element after the extra comma.
Consider another case where the extra comma is not at the end, but in the middle:
var arr = [1, 2,, 3,];<code>var arr = [1, 2,, 3,];<br>for (var i = 0; i < arr.length; i ) { alert(arr[i]); }
for (var i = 0; i < arr.length; i ) { alert(arr[i]); } CODE>
All browsers output 1, 2, undefined, 3. It can be seen that the processing method is the same, that is, inserts an undefined element before the extra comma.