Javascript_ Array

chloe·2020년 8월 17일
0

Javascript

목록 보기
1/13

Array
자바스크립트 array는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체

자바스크립트에서 배열의 길이와 요소의 자료형은 고정되어 있지 않다. 배열의 길이가 언제든지 늘어나거나 줄어들 수 있기에 JS배열들은 밀집도가 보장되어 있지 않다.

자주 사용하는 연산

1. 배열만들기

let food=['피자','치킨']
console.log(food.length)
//2

2.인덱스로 배열의 항목에 접근하기

let first=food[0]
//피자

let last= food[food.length-1]
//치킨

3. 배열의 항목들을 순환하며 처리하기

food.forEach(function(item,index,array){
  console.log(item,index)
  })
  //피자 0
    치킨 1

4. 배열 끝에 항목 추가하기

let newLength= food.push('떡볶이')
//["피자","치킨","떡볶이"]

5.배열 끝에서부터 항목 제거하기

let last=food.pop()//끝에있던'떡볶이'제거
//["피자","치킨"]

6.배열 앞에서부터 항목제거하기

let first=food.shift()// 제일 앞의 '피자'제거
//["치킨"]

7. 배열 앞에 항목 추가하기

let newLength=food.unshift('호떡') //앞에 추가
//["호떡","치킨"]

8.배열 안 항목의 인덱스 찾기

food.push('떡볶이')
//["호떡","치킨","떡볶이"]
let pos=food.indexOf("치킨")
//1

9. 인덱스 위치에 있는 항목 제거하기

let removedItem=food.splice(pos,1)//항목을 제거하는 방법
//["호떡","떡볶이"]

Splice()
_This method changes an array, by adding or removing elements from it._ 
For removing elements, we need to give the index parameter, and the number of elements to be removed.
  array.splice(index,number of elements);
 array.splice(2);// Every element starting from index2, will be removed
 
 ex) array.splice(2,1);
     let array=[1,2,3,"hello world',4.12,true];
     -->array
        (5)[1,2,"hello world",4.12,true]
        다음(4) [1,2,4.12,true]
        index2가 더이상 존재하지 않을때까지 계속 지속된다.

For adding elements, 
array.splice(index,number of elements,element,element);
As an example, add a and b in the very beginning of the array and I remove nothing. 
array.splice(0,0,'a','b');
array
(8)["a","b",1,2,3,"hello world", 4.12, true]

10.인덱스 위치에서부터 여러개의 항목 제거하기

let vegetables=['양파','무','시금치'.'파']
console.log(vegetables)
//["양파","무","시금치","파"]
let pos=1
let n =2

let removedItems= vegetables.splice(pos,n)
//배열에서 항목을 제거하는 방법
//pos 인덱스부터 n개의 항목을 제거함

console.log(vegetables)
//["양파","파"] 
console.log(removedItems)
//["무","시금치"]

11.배열복사하기

let shallowCopy=food.slice()//사본을 만드는 방법
//["호떡","떡볶이"]

Slice()
The slice() method copies a given part of an array and returns that copied part as a new array._ It doesn't change the original array._
   array.slice(from,until);
 * From: Slice the array starting from an element index
 *Until: Slice the array until another element index
 
 ex) let array=[1,2,3,"hello world",4.12,true];
     let newArray=array.slice(0,3);
     
  newArray
  (3) [1,2,3]
  array
  (6) [1,2,3,"hello world",4.12,true]


slice() splice()차이점

slice()

  • Copies elements from an array
  • Returns then as a new array
  • Doesn't change the original array
  • Starts slicing from_until given index:array.slice(from,until)
  • Slice doesn't include"until" index parameter
  • Can be used both for arrays and strings

Splice()

  • Used for adding/removing elements from array
  • Returns an array of removed elements
  • Changes the array
  • For adding elements: array.splice(index,number of elements,element)
  • For removing elements: array.splice(index,number of elements)
  • Can only be used for arrays

filter()

이 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 전환한다.
arr.filter(callback(element[,index[,array]])[,thisArg])
callback: 각 요소를 시험할 함수, true를 반환하면 요소를 유지하고 false를 반환하면 버린다.


Var numbers= [1,3,6,8,11];
var lucky= numbers.filter(function(number){
   return number>7;
});
//[8,11]

function canVote(age){
     return age >=18;
 }
 function func() {
     var filtered =[24,33,16,40].filter(canVote)
     documente.write(filtered);
     }
     func();
  //[24,33,40]

Map()

배열 내의 모든 요소 각각에 대해 제공된 콜백함수를 호출하고, 그 결과를 모아 새로운 배열을 반환한다. 기존의 배열을 콜백 함수에의해 새배열을 만드는 함수, 기존의 배열은 변하지는 않는다.
array.map(callback[,thisArg})

const arr =[0,1,2,3];
let squArr=arr.map(function(element){
      return element*element;
 });
 squArr=arr.map(element=>element*element);
 
 console.log(squArr);//[0,1,4,9]

배열 속 숫자들이 제곱되어 새로운 배열을 생성함.

출처:
https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/

(https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array)

profile
Front-end Developer 👩🏻‍💻

0개의 댓글