-
Array & Loop개발/Javascript 2022. 6. 4. 01:25
*복습 자료라서 뻔한 내용은 생략
Summary.
1. for in 구문: Object 내 Variables 순회
ex) for(let prop in obj) // {a: 3} -> property a
+ 만약 array 대상으로 할 경우 index 외에 user defined property name까지 출력하는 모양
2. for of 구문: Array 내 Elements 순회
ex) for(let i of arr) // [1,2,3] -> 1, 2, 3 접근
const arr = [3, 5, 7]; arr.foo = 'hello'; for (let i in arr) { console.log(i); // logs "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // logs 3, 5, 7 }
3. forEach 함수
let colors = ['red', 'green', 'blue'] colors.forEach(function(color) { console.log(color) }) colors.forEach(color => console.log(color))
4. Array Type은 없고 Array 라는 predefined object가 있음 (Array 관련 method가 포함됨. 예를들어 forEach)
// 기본 생성법 (다른 type인 element 섞일 수 있음) let arr = new Array(element0, element1, ..., elementN) let arr = Array(element0, element1, ..., elementN) let arr = [element0, element1, ..., elementN] let arr = Array(4) // no elements. However, arr.length === 4 // Multi-Dimensional let a = new Array(4) for (let i = 0; i < 4; i++) { a[i] = new Array(4) for (let j = 0; j < 4; j++) { a[i][j] = '[' + i + ', ' + j + ']' } } // String으로부터 만들어지는 경우 const fruits = 'Apple, Banana'.split(', '); console.log(fruits.length); // Array Copy로 만들어지는 경우 (Shallow Copy. 즉, Reference 이므로 내용 바뀌면 같이 바뀜) const fruits = ['Strawberry', 'Mango']; const fruitsCopy = [...fruits]; // ["Strawberry", "Mango"] const fruitsCopy = Array.from(fruits); // ["Strawberry", "Mango"] const fruitsCopy = fruits.slice(); // ["Strawberry", "Mango"] // Array Copy로 만들어지는 경우 (Deep Copy) const fruitsDeepCopy = JSON.parse(JSON.stringify(fruits)); // structuredClone() 이라는 함수도 있음
5. 각종 Array 연산: concat, sort, reverse, shift/unshift, slice, splice, sort, reduce, filter, map, groupBy, 등
+ thisObject를 second param으로 넘겨주는 경우도 있음
// concat let myArray = new Array('1', '2', '3') myArray = myArray.concat('a', 'b', 'c') // myArray is now ["1", "2", "3", "a", "b", "c"] // join let myArray = new Array('Wind', 'Rain', 'Fire') let list = myArray.join(' - ') // list is "Wind - Rain - Fire" // push, pop let myArray = new Array('1', '2') myArray.push('3') // myArray is now ["1", "2", "3"] myArray.pop() // slice let myArray = new Array('a', 'b', 'c', 'd', 'e') myArray = myArray.slice(1, 4) // returning [ "b", "c", "d"] // splice let myArray = new Array('1', '2', '3', '4', '5') myArray.splice(1, 3, 'a', 'b', 'c', 'd') // myArray is now ["1", "a", "b", "c", "d", "5"] // reverse let myArray = new Array('Wind', 'Rain', 'Fire') myArray.reverse() // sorts the array so that myArray = ["Fire", "Rain", "Wind"] // sort myArray.sort() // transposes the array so that myArray = ["Wind", "Rain", "Fire"] let sortFn = function(a, b) { if (a[a.length - 1] < b[b.length - 1]) return -1; if (a[a.length - 1] > b[b.length - 1]) return 1; if (a[a.length - 1] == b[b.length - 1]) return 0; } myArray.sort(sortFn) // sorts the array so that myArray = ["Wind","Fire","Rain"] // indexOf, lastIndexOf let a = ['a', 'b', 'a', 'b', 'a'] console.log(a.indexOf('b')) // logs 1 console.log(a.lastIndexOf('b')) // logs 3 // map let a1 = ['a', 'b', 'c'] let a2 = a1.map(function(item) { return item.toUpperCase() }) console.log(a2) // logs ['A', 'B', 'C'] // filter let a1 = ['a', 10, 'b', 20, 'c', 30] let a2 = a1.filter(function(item) { return typeof item === 'number'; }) console.log(a2) // logs [10, 20, 30] // every function isNumber(value) { return typeof value === 'number' } let a1 = [1, 2, 3] console.log(a1.every(isNumber)) // logs true let a2 = [1, '2', 3] console.log(a2.every(isNumber)) // logs false // some function isNumber(value) { return typeof value === 'number' } let a1 = [1, 2, 3] console.log(a1.some(isNumber)) // logs true let a2 = [1, '2', 3] console.log(a2.some(isNumber)) // logs true let a3 = ['1', '2', '3'] console.log(a3.some(isNumber)) // logs false // reduce let a = [10, 20, 30] let total = a.reduce(function(accumulator, currentValue) { return accumulator + currentValue }, 0) console.log(total) // Prints 60 // groupBy const inventory = [ { name: 'asparagus', type: 'vegetables' }, { name: 'bananas', type: 'fruit' }, { name: 'goat', type: 'meat' }, { name: 'cherries', type: 'fruit' }, { name: 'fish', type: 'meat' } ]; let result = inventory.groupBy( ({ type }) => type ); console.log(result.vegetables) // expected output: Array [Object { name: "asparagus", type: "vegetables" }]
Additional.
1. Array length 연산은 특별
let cats = [] cats[30] = ['Dusty'] console.log(cats.length) // 31 cats.length = 0; // for(let cat of cats) 하면 출력 아무 것도 안됨
2. 기본적으로 Array copy는 Shallow Copy. Deep Copy를 위해서는 JSON, 등을 활용
3. Empty Slots는 for loop에서 skip 됨
ex) const arr = [1,2, , , 4]; // 2 empty slots skipped
4. Property Enumeration
const keys = Object.keys(arr); // [ '0', '1', '4' ] for (const key in arr) console.log(key); // Logs "0 1 4"
5. label을 활용하면 break [label name]; 으로 innermost loop이 아닌 outer loop 종료도 가능
Reference.
'개발 > Javascript' 카테고리의 다른 글
Module System (0) 2022.06.05 Prototype Chain (0) 2022.06.05 Memory Management (0) 2022.06.05 Type (0) 2022.06.04 Function (0) 2022.06.03