By GokiSoft.com|
18:48 25/10/2023|
Học JS
[Share Code] Tìm hiểu Javascript - Array & Object trong JS - C2307L
#coding.js
//B1. Khai bao mang
var arr = [];
//var arr = array()
//Luu y: length: arr.length, index: 0 -> length - 1
//B2. Them cac phan tu trong mang
arr.push(10) //length: 1, index = 0
arr.push(22) //length: 2, index = 0 -> 1
arr.push(100) //length: 3, index = 0 -> 2
console.log(arr)
//B3. Lay cac phan tu trong mang
//lay dc phan tu trong mang => can biet index can lay
console.log(arr[1])
//su dung for de duyet mang
for (var i = 0; i < arr.length; i++) {
// console.log('arr['+i+'] = ' + arr[i])
console.log(`$arr[${i}] = ${arr[i]}`)
}
//B4. Xoa phan tu trong mang
//Xoa 1 phan tu trong mang -> index = 1
arr.splice(1, 1) //arr.splice(index, num): index: vi tri bat dau xoa, num: so phan tu se xoa
console.log(arr)
//B5. Chen 1 phan tu vao trong mang
//Mang hien tai: 10, 100
//Chen cac phan tu 1, 55, 22 vao mang -> 10, 1, 55, 100, 22
arr.splice(1, 0, 1)
arr.splice(2, 10, 55) //10, 1, 55
arr.splice(1, 0, 10)
arr.splice(1, 0, 1222)
arr.splice(2, 10, 55) //10, 1222, 55
console.log(arr)
arr.push(22)
console.log(arr)
//B6: Xoa het cac phan tu trong mang
arr = [];
//Phan 2: Tim hieu ve Object (Doi tuong)
//Doi tuong la gi?
//Doi tuong la khi noi ve 1 thuc the cu the
//Vi du: sinh A, tuoi: 22, gioi tinh: Nam, msv: R001 -> Doi tuong
//Lam sao chung ta co the bieu dien dc doi tuong trong JS
var std = {
'fullname': "A",
'age': 22,
'msv': 'R001',
'gender': 'Nam'
}
//key: fullname, age, msv, gender -> thuoc tinh, truong du lieu (field)
//value: A, 22, R001, Nam
//Lam the nao de truy cap dc vao thuoc tinh cua doi tuong
console.log(std.fullname)
console.log(std.age)
//Sua du lieu cho doi tuong tren
std.fullname = "TRAN VAN A"
console.log(std.fullname)
//Phan 3: Khai bao mang doi tuong
var stdList = [];
//Them 1 sinh vien vao mang
std = {
'fullname': "A",
'age': 22,
'msv': 'R001',
'gender': 'Nam'
}
stdList.push(std)
std = {
'fullname': "B",
'age': 23,
'msv': 'R002',
'gender': 'Nam'
}
stdList.push(std)
console.log(stdList)
stdList.splice(1, 50)
console.log(stdList)
stdList.push({
'fullname': 'C',
'age': 26,
'msv': 'R003',
'gender': 'ABC'
})
console.log(stdList)
#vidu2.html
<!DOCTYPE html>
<html>
<head>
<title>Javascript Tutorial</title>
<meta charset="utf-8">
<style type="text/css">
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to learn Javascript (Array & Object)</h1>
<script type="text/javascript" src="coding.js"></script>
</body>
</html>
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)