4. JavaScript Array and Method
4. JavaScript Array and Method
Array
Contents
1. Description of Array
2
1. Description of Array
• Array is JavaScript is an
object which enables
storing a collection of
multiple items under a
single variable name.
Create an array
Syntax:
4
2. How to use Array (cont.)
console.log(myArr) // []
console.log(myArr2) // []
console.log(teachers) // [ 'Reksmey', 'Chhaya', 'Dara' ]
console.log(students) // [ 'Chiva', 'Tola', 'Makara' ]
5
2. How to use Array (cont.)
console.log(arr[2]) // Dara
console.log(arr[arr.length-1])
*** You can get the size of array of using property length.
6
2. How to use Array (cont.)
Output:
Banana,Orange,Lemon,Kiwi,Mango
7
2. How to use Array (cont.)
8
2. How to use Array (cont.)
Copy Array
const fruits = ['Apple', 'Banana', 'Grape']
// create a copy using spread syntax
const fruitsCopy = [...fruits]
// create a copy using the from() method
const fruitsCopy2 = Array.from(fruits)
9
2. How to use Array (cont.)
Objects in Array
let personObj = {
"id": 100,
"name": "Chan Dara",
"nationality": "Khmer"
}
let personObj2 = {
"id": 101,
"name": "Jack Square",
"nationality": "English"
}
console.log(persons)
10
2. How to use Array (cont.)
11
JSON
13
1. Overview
A JSON string can be stored in its own file, which is basically just a text file
with an extension of .json, and a MIME type of application/json.
JSON Structure
• You can include the same basic data types inside JSON as you can in a
standard JavaScript object — strings, numbers, arrays, booleans, and
other object literals. This allows you to construct a data hierarchy, like so:
15
1. Overview {
"fullname": "Reksmey",
Syntax "age": 25,
"major": "IT",
{ "position": "Manager",
"key" : value "specialized": [
}
"Web Design",
"iOS App Development",
"React Native",
"Spring Framework",
"DevOps",
"Managment & Leadership",
"Project Mentor"
],
"remark": "R & D Department",
"status": true
}
16
1. Overview
Other notes
• JSON is purely a string with a specified data format — it contains only
properties, no methods.
• JSON requires double quotes to be used around strings and property names.
Single quotes are not valid other than surrounding the entire JSON string.
• Even a single misplaced comma or colon can cause a JSON file to go wrong,
and not work.
• JSON can actually take the form of any data type that is valid for inclusion
inside JSON, not just arrays or objects. So for example, a single string or
number would be valid JSON.
• Unlike in JavaScript code in which object properties may be unquoted, in
JSON only quoted strings may be used as properties.
17
2. Exchange Data
18
2. Exchange Data
• We retrieve the response as text rather than JSON, by calling the text() not
json() method of the response.
19
Thank you
Perfect Practice, Does Perfect Thing
20