Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:10:00
Original
1744 people have browsed it

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,}; /* 正确 */
Copy after login

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,); /* 正确 */
Copy after login

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,); //报错
Copy after login

For objects, there cannot be a trailing comma.

var o = { name:'赵', age:12 }; // 正确
var o = { name:'赵', age:12,}; // 报错
Copy after login

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格式
Copy after login

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,}); // 解析会发生错误
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template