Each language has its own special place, for JavaScript, using VAR can declare any type of variable, the script language seems simple, but want to write elegant code is need to accumulate experience. This article makes a list of seven details that JavaScript beginners should pay attention to and share with you.
(1) Simplified code
JavaScript defines objects and arrays very simply, we want to create an object, which is generally written like this:
var car = new Object ();
Car.colour = ' red ';
Car.wheels = 4;
Car.hubcaps = ' spinning ';
Car.age = 4;
The following wording can achieve the same effect:
var car = {
Colour: ' Red ',
Wheels:4,
Hubcaps: ' Spinning ',
Age:4
}
The latter is much shorter, and you don't need to repeat the name of the object.
In addition to the array also has a concise way of writing, in the past we declared that the array is written like this:
var moviesthatneedbetterwriters = new Array (
' Transformers ', ' Transformers2 ', ' Avatar ', ' Indiana Jones 4 '
);
The more concise notation is:
var moviesthatneedbetterwriters = [
' Transformers ', ' Transformers2 ', ' Avatar ', ' Indiana Jones 4 '
];
For arrays, there is an associative array such a special thing. You will find a lot of code that defines objects like this:
var car = new Array ();
car[' colour '] = ' red ';
Car[' wheels '] = 4;
car[' hubcaps '] = ' spinning ';
Car[' age '] = 4;
This is crazy, don't be confused, "associative array" is just an alias of an object.
Another way to simplify the code is to use the ternary operator, for example:
var direction;
if (x < 200) {
Direction = 1;
} else {
Direction =-1;
}
We can replace this notation with the following code:
1 var direction = x < 200? 1:-1;
(2) using JSON as the data format
The great Douglas Crockford invented the JSON data format to store data, and you can use native JavaScript methods to store complex data without having to make any additional transformations, such as:
var band = {
"Name": "The Red hot Chili peppers",
"Members": [
{
"Name": "Anthony Kiedis",
"Role": "Lead vocals"
},
{
"Name": "Michael ' Flea ' Balzary",
"Role": "Bass guitar, trumpet, backing vocals"
},
{
"Name": "Chad Smith",
"Role": "Drums,percussion"
},
{
"Name": "John Frusciante",
"Role": "Lead Guitar"
}
],
"Year": "2009"
}
You can use JSON directly in JavaScript, even as a format returned by the API, to be applied in many APIs, such as:
function Delicious (o) {
var out = '
Seven details to note for JavaScript beginners