Hiển thị array => sử dụng chính tên của array đó
hiển thị object => khá phức tạp
for(var key in objects) {
var value = objects[key];
}
Tham khảo thêm:
https://stackoverflow.com/questions/7306669/how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key/16643074#16643074
Monday, September 25, 2017
JSON
JavaScript Object Notation
Ví dụ
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
JSON Syntax Rules
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
Ví dụ
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
Version
ECMAScript 6 is also called ECMAScript 2015.
ECMAScript 7 is also called ECMAScript 2016.
ECMAScript 7 is also called ECMAScript 2016.
Browser Support
ECMAScript 3 is fully supported in all browsers.ECMAScript 5 is fully supported in all modern browsers*.
ECMAScript 6 is partially supported in all modern browsers.
ECMAScript 7 is poorly supported in all browsers.
ECMAScript Browser Implementations
Engine | ECMA | Browser |
---|---|---|
V8 | 6 | Chrome (Partial Support) |
SpiderMonkey | 6 | Firefox (Partial Support) |
Chakra | 6 | Edge (Partial Support) |
Nitro | 6 | Safari (Partial Support) |
V8 | 6 | Opera (Partial Support) |
V8 | 5 | Chrome 23 |
SpiderMonkey | 5 | Firefox 21 |
JavaScript 1.8.5 | 5 | Firefox 4 |
Nitro | 5 | Safari 6 |
V8 | 5 | Opera 15 |
Chakra | 5 | Edge 12 |
Chakra | 5 | IE 10 |
Performance
- Reduce Activity in Loops
- Reduce DOM Access
- Reduce DOM Size
- Avoid Unnecessary Variables
- Delay JavaScript Loading
- Avoid Using with
Common mistakes
- Accidentally Using the Assignment Operator
- Expecting Loose Comparison
- Confusing Addition & Concatenation
- Misunderstanding Floats
- Breaking a JavaScript String
- Misplacing Semicolon
- Breaking a Return Statement
- Accessing Arrays with Named Indexes
- Ending Definitions with a Comma
- Undefined is Not Null
- Expecting Block Level Scope
Sunday, September 24, 2017
Best Practices
Avoid Global Variables
Always Declare Local Variables
Local variables must be declared with the var keyword, otherwise they will become global variables.Initialize variables when you declare them.
Never Declare Number, String, or Boolean Objects
Don't Use new Object()
- Use {} instead of new Object()
- Use "" instead of new String()
- Use 0 instead of new Number()
- Use false instead of new Boolean()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new Function()
Beware of Automatic Type Conversions
Use === Comparison
The == comparison operator always converts (to matching types) before comparison.The === operator forces comparison of values and type:
Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined.Undefined values can break your code. It is a good habit to assign default values to arguments.
<script>
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>
End Your Switches with Defaults
Avoid Using eval()
Conventions
JS Hoisting
hoist: trong tiếng anh nghĩa là "nâng lên"
javascript luôn tự động đưa các declaration lên trên.(the top of the current scope) (vì thế mà sd 1 biến trước khi khai báo trong javascript không gây lỗi)
tuy nhiên javascript lại KHÔNG tự động đưa các initialization lên trên (vì thế mà sd 1 biến chưa khởi tạo sẽ hiển thị undefined)
----
sử dụng use strick sẽ làm cho javascript không thực hiện hoisting nữa => phải khai báo biến trước khi sd
"use strict";
--------
https://www.w3schools.com/Js/js_conventions.asp
hoist: trong tiếng anh nghĩa là "nâng lên"
javascript luôn tự động đưa các declaration lên trên.(the top of the current scope) (vì thế mà sd 1 biến trước khi khai báo trong javascript không gây lỗi)
tuy nhiên javascript lại KHÔNG tự động đưa các initialization lên trên (vì thế mà sd 1 biến chưa khởi tạo sẽ hiển thị undefined)
----
sử dụng use strick sẽ làm cho javascript không thực hiện hoisting nữa => phải khai báo biến trước khi sd
"use strict";
--------
https://www.w3schools.com/Js/js_conventions.asp
Web browser market share
Desktop/laptop browser statistics | ||||
---|---|---|---|---|
Google Chrome |
|
62.09% | ||
Mozilla Firefox |
|
14.81% | ||
Internet Explorer |
|
9.62% | ||
Safari |
|
5.34% | ||
Microsoft Edge |
|
3.68% | ||
Opera |
|
1.6% | ||
Yandex Browser |
|
0.5% | ||
Coc Coc |
|
0.29% | ||
UC Browser |
|
0.24% | ||
Chromium |
|
0.18% | ||
Sogou Explorer |
|
0.16% | ||
Maxthon |
|
0.16% | ||
360 Secure Browser |
|
0.16% | ||
QQ Browser |
|
0.11% | ||
Mozilla Suite |
|
0.04% | ||
Phantom |
|
0.03% | ||
Vivaldi |
|
0.03% | ||
Pale Moon |
|
0.02% | ||
Amigo |
|
0.02% | ||
SeaMonkey |
|
0.02% | ||
Other |
|
0.06% | ||
Desktop web browser market share according to StatCounter for February 2017.[19] |
Debugging
Các bước để bật giao diện debug: ấn F12 => chọn console
sử dụng console.log(); để hiển thị lên giao diện console
sử dụng từ khóa debugger để đặt breakpoint
Với các trình duyệt cụ thể
Chrome và IE: Tool => developer tool => vào tab console
Firefox: cài firebug
sử dụng console.log(); để hiển thị lên giao diện console
sử dụng từ khóa debugger để đặt breakpoint
Với các trình duyệt cụ thể
Chrome và IE: Tool => developer tool => vào tab console
Firefox: cài firebug
Javascript RegExp
Cú pháp
/pattern/modifierVí du
var x=/w3schools/i;Modifier
Modifier | Description |
---|---|
i | Perform case-insensitive matching |
g | Perform a global match (find all matches rather than stopping after the first match) |
m | Perform multiline matching |
Bracket
sử dụng để tìm một khoảng các ký tựExpression | Description |
---|---|
[abc] | Find any character between the brackets |
[^abc] | Find any character NOT between the brackets |
[0-9] | Find any character between the brackets (any digit) |
[^0-9] | Find any character NOT between the brackets (any non-digit) |
(x|y) | Find any of the alternatives specified |
Metacharacters
Các ký tự có ý nghĩa đặc biệtMetacharacter | Description |
---|---|
. | Find a single character, except newline or line terminator |
\w | Find a word character |
\W | Find a non-word character |
\d | Find a digit |
\D | Find a non-digit character |
\s | Find a whitespace character |
\S | Find a non-whitespace character |
\b | Find a match at the beginning/end of a word |
\B | Find a match not at the beginning/end of a word |
\0 | Find a NUL character |
\n | Find a new line character |
\f | Find a form feed character |
\r | Find a carriage return character |
\t | Find a tab character |
\v | Find a vertical tab character |
\xxx | Find the character specified by an octal number xxx |
\xdd | Find the character specified by a hexadecimal number dd |
\uxxxx | Find the Unicode character specified by a hexadecimal number xxxx |
Quantifiers
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{X} | Matches any string that contains a sequence of X n's |
n{X,Y} | Matches any string that contains a sequence of X to Y n's |
n{X,} | Matches any string that contains a sequence of at least X n's |
n$ | Matches any string with n at the end of it |
^n | Matches any string with n at the beginning of it |
?=n | Matches any string that is followed by a specific string n |
?!n | Matches any string that is not followed by a specific string n |
Methods
Method | Description |
---|---|
exec() | Tests for a match in a string. Returns the first match |
test() | Tests for a match in a string. Returns true or false |
toString() | Returns the string value of the regular expression |
Các phương thức khác (không phải của lớp RegExp)
có 2 phương thức của lớp string
search();//trả về vị trí của phần tử match với regexp
replace(); trả về string đã bị thay đổi
Ví dụ
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);// trả về 6
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");//trả về 'Visit W3Schools!'
Sunday, September 17, 2017
undefined và null
typeof trả về kiểu dữ liệu
typeof undefined // undefined
typeof null // object
toán tử == equal to
toán tử === equal value and equal type
null === undefined // falsenull == undefined // true
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
typeof undefined // undefined
typeof null // object
toán tử == equal to
toán tử === equal value and equal type
null === undefined // falsenull == undefined // true
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
Javascript syntax
Values (giá trị)
Có 2 loại gía trị trong JS:- Fixed value (các gía trị đã fix) còn được gọi là Literal
- number: khai báo chỉ được phép sử dụng số và dấu chấm thập phân
- tất cả một gía trị kiêu number đều là số thực 64 bit
- NaN: typeof NAN tra về kiểu number
- NaN có ý nghĩa là số không hợp lệ
- Infinity và -Infinity có nghĩa là gía trị nằm ngoài gioi hạn của kiểu number
- string: khai báo sử dụng nháy kép " hoặc nháy đơn '
- thuộc tính length để biết độ dài của string
- sử dụng escapse character \ => để chèn những ký tự đặc biệt vào string: var s = 'It\'s alright';
- boolean: chỉ có 2 giá trị true false
- sử dụng hàm Boolean(x) để xác định true false
- các toán tử so sánh == === > <
- undefined: có giá trị là undefined
- object:
- kiểu dữ liệu mảng cũng là 1 object ["a",1,2,true,false,undefined,1e-4]
- kiểu null cũng là 1 object: typeof null sẽ trả về object
- function: typeof function myFunc(){} sẽ trả về function
- Variable value (các gía trị có thể thay đổi) còn được gọi là Variable
- khai báo sử dụng từ khóa var và định danh (id): var x =6;
- gía trị mặc định khi không gán gía trị cho x là undefined
- khai báo định danh cho biến: NÊN sử dụng Lower Camel Case (firstName, lastName,interCity)
- JS sử dụng kiểu dữ liệu động (biến x ở trên có thể gán bất kỳ giá trị của bất kỳ KDL nào mà không gây lỗi)
- biến có 2 loại phạm vi: local và global
- biến được khai báo trong 1 function là local (var x=9;)
- biến khai báo mà không sd từ khóa var là biến global (x=9;) bất kể nó đươc khai báo ở trong một hàm
Operator (toán tử)
- 7 loai: + - * / % ++ --
- toán tử gán =
- so sánh:
- == equal to
- === equal value and equal type
- != not equal
- !== not equal value or not equal type
- variablename = (condition) ? value1:value2
- logic:
- && and
- || or
- ! not
- type
- typeof X: trả về kiểu của variable
- instanceof trả về true nếu kiểu của đối tượng là đúng
- thứ tự ưu tiên các toán tử:
- nhân chia trước, cộng trừ sau (phép nhân và phép chia cùng thứ tự ưu tiên, phép cộng và phép trừ cùng thứ tự ưu tiên)
- trong 1 biểu thức nếu các toán t ử có cùng thứ tự ưu tiên => thực hiện biểu thức từ trái sang phải. (Vd: 6/2*3 trả về 3*3, không trả về 6/6)
- toán tử ( và ) là có thứ tự ưu tiên cao nhất
Expressions (biểu thức)
- cộng chuỗi : "str1"+"str2" thực ra là nối chuỗi
- trừ chuỗi: "str1"-"1" trả về NaN (typeof NAN trả về number )
- cộng số: 5+6 trả về 11
- cộng chuỗi và số sẽ trả về chuỗi
- "5"+ 2 + 3 sẽ trả về "523"
- 2 + 3 + "5" sẽ trả về "55"
Keywords (từ khóa)
Để định nghĩa hành động sẽ được JS thực hiệnLet this long package float,
Goto private class if short.
While protected with debugger case,
Continue volatile interface.
Instanceof super synchronized throw,
Extends final export throws.
Try import double enum?
- False, boolean, abstract function,
Implements typeof transient break!
Void static, default do,
Switch int native new.
Else, delete null public var
In return for const, true, char
…Finally catch byte.
Comments
- sử dụng double slashes // code
- sử dụng /* code */
Identifiers (định danh)
sử dụng để đặt tên cho- biến variable
- từ khóa keyword
- hàm function
- nhãn label
- ký tự đầu tiên: chữ, dấu $, dấu _
- các ký tự sau: chữ, dấu $, dấu _ , số
JavaScript is Case Sensitive
Vì thế mà JS sẽ không xem VAR hay Var là một từ khóa như varStatement (câu lệnh)
sử dụng dấu ; để ngăn cách các câu lệnhsử dụng {} để mô tả 1 code block
Function
Cú pháp:function name(parameter1, parameter2, parameter3) {
code to be executed
return something; (có thể không có return cũng được)
}
Gọi hàm:
name(argument1,argument2,argument3);
Gọi ra nội dung hàm:
name;
Object
Gán biến person cho một objectvar person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
person.firstName;
person["firstName"];
person.fullName(); sẽ trả về "John Doe"
person.fullName; sẽ trả về định nghĩa hàm
function() {
return this.firstName + " " + this.lastName;
}
so sánh 2 đối tượng (x==y) và (x===y) luôn trả về false (do x và y luôn khác gía trị, mặc dù cùng kiểu là object)
Event
<element event='some JavaScript'>Các loại event phổ biến:
Event | Description |
---|---|
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
Array
khai báovar cars=['volvo','toyota','chervolet'];
truy nhập
cars[0] cars[1] hoặc cars
typeof cars trả về kiểu object
cars.length trả về độ dài của mảng
phân biệt array và object
array sử dụng numbered indexes
object sử dụng named indexes
để giup phân biệt array và object trong code, có 3 cách
1. sự dụng hàm Arrays.isArray(cars);
2. tạo hàm mới
function isArray(x){return x.constructor.toString().indexOf("Array") > -1;}
3. sư dụng cars instanceof Array;
Một số array function:
pop() push() => biến array thành stack, thêm bơt phần tử vào cuối array
shift() unshift() => thêm bớt phần tử vào đầu array
slice(start,remove_nunber,insert_elements); => để thêm và xóa phần tử vào giua array
arr1.concat(arr2,arr3); nối2 mảng
Sắp xếp mảng
sort() se sắp xếp theo thứ tự alphabet
sort(function(a,b){return a-b;}) sẽ sd một hàm compare để sắp xếp
reverse() đảo ngược lại thứ tự các thành phần trong array
Conditions
if(dk1){}elseif(dk2){}
else{//th còn lại}
switch(val):
case 1: break;
case 2: break;
default:...
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
Loops
forfor (statement 1; statement 2; statement 3) {
code block to be executed
}
s1: câu lệnh được thực hiện trước khi thực hiện vòng lặp
s2: câu lệnh điều kiện để thực hiện lăp
s3: câu lệnh được thực hiện sau mỗi vòng lặp
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
for in
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x]; // trả về John Doe 25
}
kiểm tra điều kiện condition trước khi bắt đầu vòng lặp
while (condition) {
code block to be executed
}
thực hiện vòng lặp 1 lần, rồi kiểm tra điều kiện condition trước khi thực hiện mỗi vòng lặp mới
do {
code block to be executed
}
while (condition);
break; // nhảy ra khỏi vòng lặp
continue; // nhảy đến lần lặp tiếp theo
Type conversion
5 kiểu dữ liệu có chứa giá tri
number
string
boolean
function
object
3 kiểu dữ liệu trả về object với toán tử typeof
Object
Array
Date
2 kiểu dữ liệu không chứa giá trị
null
undefined
toán tử typeof
typeof "John"
// Returns "string"
typeof 3.14
// Returns "number"
typeof NaN
// Returns "number"
typeof false
// Returns "boolean"
typeof [1,2,3,4] // Returns
"object"
typeof {name:'John', age:34}
// Returns "object"typeof new Date()
// Returns "object"typeof function () {} // Returns
"function"
typeof myCar
// Returns "undefined" *
typeof null
// Returns "object"
typeof undefined
// Returns "undefined"
vì thế không thể sử dụng toán tử typeof để kiểm tra 1 đối tượng là Object hay Array. mà phải sử dụng thuộc tính constructor
"John".constructor
// Returns function String() {[native code]}
(3.14).constructor
// Returns function Number() {[native code]}
false.constructor // Returns
function Boolean() {[native code]}
[1,2,3,4].constructor
// Returns function Array() {[native code]}
{name:'John',age:34}.constructor
// Returns function Object() {[native code]}
new Date().constructor
// Returns function Date() {[native code]}
function () {}.constructor // Returns
function Function(){[native code]}
kiểm tra 1 đối tượng có phải là Array không
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
hoặc
function isArray(myArray) {
return myArray.constructor
=== Array;
}
Error
try {
Block of code to try
throw something;// có thể thêm throw vào trong code
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
JS có một error object được build sẵn, có 2 thuộc tính sau
name: loại lỗi
message: nội dung lỗi
có các loại lỗi chuẩn sau
Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred
Output (hiển thị dữ liệu)
JavaScript can "display" data in different ways:
- Writing into an HTML element, using innerHTML.
- sử dụng phương thức document.getElementById(id)
- Writing into the HTML output using document.write().
- nếu hàm này được thực hiện sau khi page đã load xong, nó sẽ xóa toàn bộ dữ liệu html trong page
- vì vậy nên chỉ sd để testing
- Writing into an alert box, using window.alert().
- hiển thị dl sd hộp thoại cảnh bảo alert box
- Writing into the browser console, using console.log().
- sửdụngđểdebugging
where to put javascript code?
Internal javascript
<script>javascript code</script>
Có thể đặt cặp thẻ script ở <head> và <body>
Tuy nhiên nếu đặt mã js ở cuối file html thì sẽ cải thiện thời gian load trang (vì dịch mã js sẽ làm chậm việc hiển thị file html lên cửa sổ trình duyệt)
External JavaScript
sử dụng file.jstái sử dụng được ở nhiều file html khác nhau
sử dụng
<script src="myScript.js"></script> để chèn javascript vào file html
3 lợi ích khi sd external javascript:
phân tách dữ liệu(html,css) và code (javascript)
dễ đọc và bảo trì
các file js đã được cached làm tăng tốc độ page loads
JavaScript can do
JavaScript accepts both double and single quotes
JavaScript Can Change HTML Content
document.getElementById("demo").innerHTML = "Hello JavaScript";
JavaScript Can Change HTML Attributes
document.getElementById('myImage').src='pic_bulbon.gif'JavaScript Can Change HTML Styles (CSS)
document.getElementById("demo").style.fontSize = "25px";JavaScript Can Hide HTML Elements
document.getElementById("demo").style.display = "none";JavaScript Can Show HTML Elements
document.getElementById("demo").style.display = "block";
Subscribe to:
Posts (Atom)