JavaScript
Arrays
WebDevLee
2021. 10. 14. 18:04
이 글은 자바스크립트의 Array(배열)에 관한 개념 및 문법을 정리하기 위해 작성하였습니다.
< Arrays >
To organize and store data.
You can think of array as List in real life.
- Arrays can store any data type (including strings, numbers, and booleans)
< Create an Array >
To create an array.
let Array = [element1, element2, element3 ...]
- The array is represented by square brackets : [ ]
- Each content item inside an array is called an element
< Accessing Elements >
To access each element in an array.
Array[index]
- Use bracket notation [ ], with the index after the name of the array to access the element.
- Arrays in Javascript are zero-indexed, meaning the positions start counting from 0 rather than 1.
ex)
let destination = ['Finland', 'America', 'Uyuni'];
destination[0]; // Finland
// You can also access individual characters in a string using [ ] and index.
let hello = 'Hello World';
hello[3]; // l
< Update Elements >
Once you have access to an element in an array, you can update its value.
ex)
let seasons = ['Winter', 'Spring', 'Summer', 'Fall'];
seasons[3] = 'Autumn';
console.log(seasons); // ['Winter', 'Spring', 'Summer', 'Autumn']
< Arrays with let and const >
- Let : mutable O, Reassign O
- Const : mutable O, Reassign X
ex)
let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];
const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];
condiments[0] = 'Mayo'; // condiments : ['Mayo', 'Mustard', 'Soy Sauce', 'Sriracha']
condiments = ['Mayo']; // condiments : ['Mayo']
utensils[3] = 'Spoon'; // utensils : ['Fork', 'Knife', 'Chopsticks', 'Spoon']
utensils = ['Spoon']; // -----TypeError-----
< The .length property >
To access how many elements are in an array.
ex)
let destination = ['Finland', 'Japan', 'Singapore', 'Uyuni', 'Vietnam'];
console.log(destination.length); // 5
< The .push() Method >
To add item to the end of an array.
- .push() can take a single argument or multiple arguments seperated by commas.
ex)
let array = ['item0', 'item1', 'item2'];
array.push('item3', 'item4');
console.log(array); // ['item0', 'item1', 'item2', 'item3', 'item4'];
< The .pop() Method >
To remove the last item of an array.
- .pop() does not take any arguments.
- .pop() returns the value of the last element.
ex)
const destination = ['Europ', 'Asia', 'America', 'Africa'];
const removed = destination.pop();
console.log(destination); // ['Europ', 'Asia', 'America']
console.log(removed); // 'Africa'
+. More Array Methods : .shift(), .unshift(), .slice(), indexOf() ...
< Arrays and Functions >
If the array is mutated inside the function, that change will be maintained outside the function as well.
ex)
const alphabet = ['a', 'b', 'c'];
function changeArr(arr) {
arr[0] = 'A';
}
changeArr(alphabet);
console.log(alphabet); // ['A', 'b', 'c']
< Nested Array >
- Array can contain another array.
ex)
const numberClusters = [[1, 2], [3, 4], [5, 6]];
const target = numberClusters[2][1];
console.log(target); // 6