-
7. Array, APIJavaScript & TypeScript 2020. 11. 14. 14:17
Array
1. Declaration
const arr1 = new Array(); const arr2 = [1, 2];
2. Index position
const fruits = ['apple', 'banana']; console.log(fruits); // 'apple', 'banana' console.log(fruits.length); // 2 console.log(fruits[0]); // 'apple' console.log(fruits[1]); // 'banana' console.log(fruits[2]); // undefined console.log(fruits[fruits.length - 1]); // 'banana'
3. Looping over an array
- print all fruits
// a. for for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // b. for of for (let fruit of fruits) { console.log(fruit); } // c. forEach fruits.forEach((fruit, index) => console.log(fruit));
4. Addition, deletion, copy
// push: add an item to the end fruits.push('berry', 'peach'); console.log(fruits); // 'apple', 'banana', 'berry', 'peach' // pop: remove an item from the end fruits.pop(); fruits.pop(); console.log(fruits); // 'apple', 'banana' // unshift: add an item to the beginning fruits.unshift('berry', 'remon'); console.log(fruits); // 'berry', 'remon', 'apple', 'banana' // shift: remove an item to the beginning fruits.shift(); fruits.shift(); console.log(fruits); // 'apple', 'banana' // note!! shift, unshift are slower than pop, push // splice: remove an item by Index position fruits.push('berry', 'peach', 'remon'); console.log(fruits); // 'apple', 'banana', 'berry', 'peach', 'remon' fruits.splice(1, 1); // 1부터 1개 지워줘 console.log(fruits); // 'apple', 'berry', 'peach', 'remon' fruits.splice(1, 1, 'apple', 'watermelon'); // 1부터 1개 지우고 사과와 수박을 넣어줘 console.log(fruits); // 'apple','apple', 'watermelon' 'peach', 'remon' // combine two arrays const fruits2 = ['mango', 'coconut']; const newFruits = fruits.concat(fruits2); console.log(newFruits); // 'apple','apple','watermelon','peach','remon','mango','coconut'
5. Searching
// indexOf: find the index console.log(fruits.indexOf('apple')); // 0 console.log(fruits.indexOf('watermelon')); // 2 console.log(fruits.indexOf('coconut')); // -1 // includes : 포함하고 있느가 ? console.log(fruits.includes('apple')); // true console.log(fruits.includes('king')); // false // lastIndexOf : 제일 마지막에 있는거 console.log(fruits.lastIndexOf('apple')); // 1
※출처
www.youtube.com/channel/UC_4u-bXaba7yrRz_6x6kb_w
'JavaScript & TypeScript' 카테고리의 다른 글
9. JSON (0) 2020.11.15 8. Array APIs (0) 2020.11.14 6. what is object (0) 2020.11.14 5. class vs object (0) 2020.11.14 4. Arrow Function (0) 2020.11.13