Home > Article > Web Front-end > A brief analysis of whether there can be a comma after the last element when assigning values to C/C++, Java, PHP, JavaScript, Json arrays and objects_javascript skills
1 C, C++, Java, and PHP all tolerate trailing commas
When assigning values to arrays in C, C++, and Java, the comma at the end of the last element is optional. The following two lines of code are equivalent for these languages.
int a[] = {1,2,3}; /* 正确 */ int a[] = {1,2,3,}; /* 正确 */
PHP also inherits the characteristics of C. The following two lines of code are equivalent.
$a = array(1,2,3); /* 正确 */ $a = array(1,2,3,); /* 正确 */
2 JavaScript treats the trailing comma as a syntax error!
However, when it comes to JavaScript, the situation is very different. There must be no comma at the end of the last element, otherwise it will be a syntax error.
var a = new Array(1,2,3); //正确 var a = new Array(1,2,3,); //报错
For objects, there cannot be a trailing comma.
var o = { name:'赵', age:12 }; // 正确 var o = { name:'赵', age:12,}; // 报错
Although some browsers are most tolerant after detecting this error, this is not a uniform behavior. IE series browsers cannot tolerate this kind of error.
3 JSON also cannot tolerate trailing commas
{"name":"zhao", "age":12} // 正确的JSON格式 {"name":"zhao", "age":12,} // 错误的JSON格式
It should be noted that JSON is a universal data format and has nothing to do with specific programming languages. Various languages also use different tolerance levels when decoding JSON. PHP's json_decode() does not tolerate trailing commas.
json_decode({"name":"zhao", "age":12,}); // 解析会发生错误
The editor will tell you so much about whether there can be a comma after the last element when assigning values to C/C++, Java, PHP, JavaScript, Json arrays and objects. I hope it will be helpful to you. If you want to know more For information, please log in to the official website of Script House for details!