동캄의 코딩도장

JS [array] 본문

front/HTML&CSS&JS

JS [array]

동 캄 2022. 1. 24. 12:09
'use strict'

// Array

// 1. Declaration
const arr1 = new Array();
const arr2 =[1,2];

// 2. Index position
const fruits =['apple','banana'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);

// 3. Looping over an array

// 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)=>console.log(fruit));

// 4. Addition, deletion, copy
// push: add an item to the end
fruits.push('starwberry','peach');

//pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);

//unshift: add an item to the beginning
fruits.unshift('lemon','blueberry');
console.log(fruits);

//shift: remove an item from the beginning
fruits.shift();
console.log(fruits);

// note!! shift, unshift are slower than pop, push

// splice: remove an item by index position

fruits.push('peach','lemon','blueberry');
console.log(fruits);
fruits.splice(1,1); // index 1 삭제
console.log(fruits)
fruits.splice(1,1,'melon','watermelon'); // index 1 삭제 후, melon watermelon 추가

//combine two arrays
const fruits2=['pear','coconut'];
const newFruits=fruits.concat(fruits2)
fruits.pop();
// 5. searching

console.log(fruits)
console.log(fruits.indexOf('melon'));  
console.log(fruits.indexOf('potato'));  //없으면 -1 리턴

//includes
console.log(fruits.includes('apple')); //있으면 true 리턴
console.log(fruits.includes('potato')); //없으면 false 리턴

// lastIndexOf
fruits.push('apple');
console.log(fruits);
console.log(fruits.lastIndexOf('apple')); // 마지막 원소의 index 리턴

console.log(fruits.toString());
// console.log(fruits.join('j'));
fruits.reverse();
console.log(fruits);

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [JSON]  (0) 2022.01.25
JS [array API]  (0) 2022.01.24
JS [Object]  (0) 2022.01.24
JS [Class]  (0) 2022.01.24
JS [function]  (0) 2022.01.23