[ javascript ] 배열 입력, 추가, 삭제, 출력 등 배열의 활용 push, pop, shift, unshift, indexOf, splice, concat, includes, lastIndexOf, forEach, for of > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] 배열 입력, 추가, 삭제, 출력 등 배열의 활용 push, pop, shift, unshift, i…

작성일 21-02-14 02:14

페이지 정보

작성자 웹지기 조회 1,905회 댓글 0건

본문

 '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]); //맨처음 배열은 0

console.log(fruits[1]);

console.log(fruits[fruits.length-1]); //맨마지막 배열은 배열의 길이 -1

console.clear();


3. Looping over an array

print all fruits

for(let i=0; i<fruits.length; i++) {

    console.log(fruits[i]);

}

console.clear();


for of

for(let fruit of fruits) {

    console.log(fruit);

}

console.clear();


forEach

/*

 * 사용방법 

 * 배열.forEach(function(변수정의, 인덱스, 들어가있는 배열값) { 출력문});

fruits.forEach(function(fruit, index, array) {

    console.log(fruit, index, fruits);

});

*/

한줄로 간단하게

fruits.forEach((fruit)=>console.log(fruit));

console.clear();


4. Addtion, deletion, copy

맨마지막에 배열을 추가

push : add an item to the end

fruits.push('melon', 'watermelon');

console.log(` push : ${fruits}`);


맨마지막의 배열을 삭제

pop : remove an item from the end

fruits.pop();

console.log(` pop : ${fruits}`);


맨앞에 배열을 추가

unshift: add an item to the benigging

fruits.unshift('cherry', 'pear');

console.log(` unshift : ${fruits}`);


맨앞에 배열을 삭제

shift: remove an item from teh benigging

fruits.shift();

console.log(` shift : ${fruits}`);


shift, unshft는 pop과 push보다 느리다

pop과 push는 맨뒤의 공간을 활용해서 넣다 뺏다 하기때문에

배열의정렬이 움직이지 않아도 되기때문에 더 빠르다.

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


splice : remove an item by index position

fruits.splice(1,1); splice(시작하는 인덱스, 삭제 인덱스 개수);

삭제인덱스개수가 1이면 해당인덱스만, 2면 해당인덱스와 그다음 인덱스까지 삭제

splice(시작하는 인덱스); 만 적을경우 해당하는 인덱스를 포함해서 뒤로 모두 지워버린다.

fruits.push('pear');

console.log(fruits);

fruits.splice(1,1);

console.log(fruits);

 

삭제와 추가가 동시에 가능 splice(시작하는인덱스, 삭제 인덱스 개수, '추가할인덱스', '추가할인덱스')

fruits.splice(1, 1, 'tometo', 'banana');

console.log(fruits);


combine two arrays

첫번째 선언된 fruits 배열과 fruits2를 하나로 합치는 함수 :: concat

첫번째배열.concat(두번째배열)

const fruits2 = ['apple', 'banana'];

const newFruits = fruits.concat(fruits2);

console.log(newFruits);


5. Searching

find the index

값이 있을경우 index번호 없을 경우 -1

console.clear();

console.log(fruits);

console.log(fruits.indexOf('apple'));


find of includes

값이 있을경우 true, 없을 경우 false

console.log(fruits.includes('apple'));


lastIndeOf 

중복이 되었거나 할 때 맨첫번째 나오는 값만을 출력한다.

이럴때 제일뒤에 위치한 중복배열을 불러올 때 사용한다.

fruits.push('apple');

console.clear();

console.log(fruits);

console.log(fruits.indexOf('apple'));

console.log(fruits.lastIndexOf('apple'));



추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기