JavaScript - Array Methods 1

LANA·2020년 4월 6일
0

JavaScript

목록 보기
3/21
post-thumbnail

배열 판별하기

let words = ['피', '땀', '눈물'];
typeof words // 'object' // array라고 나오지 않음
Array.isArray(words); // true --- 배열을 판별하는 메소드가 따로 존재합니다

Array.isArray(object) -IMMUTABLE

  • 전달인자: 검사할 대상
  • 리턴 값: true 또는 false
  • 검사할 대상이 배열이면 true, 아니면 false를 반환
Array.isArray([]) // true
Array.isArray(['code', 'states']) // true
Array.isArray({ hello: 'world' }) // false
Array.isArray('some text') // false
Array.isArray(undefined) // false

array.indexOf(element) -IMMUTABLE

  • 전달인자: 찾고자 하는 element
  • 리턴 값: 배열 내에 최초로 element가 등장하는 index, 만일 없으면 -1을 리턴
let words = ['Radagast', 'the', 'Brown'];
words.indexOf('Radagast') // 0
words.indexOf('the') // 1
words.indexOf('Brown') // 2
words.indexOf('brown') // -1
words.indexOf('nonexistent') // -1

array.includes(element) -IMMUTABLE

  • 전달인자: 찾고자 하는 element
  • 리턴 값: 배열 내에 element가 있으면 true, 없으면 false
let words = ['Radagast', 'the', 'Brown'];
words.includes('Radagast') // true
words.includes('the') // true
words.includes('Brown') // true
words.includes('brown') // false
words.includes('nonexistent') // false

function hasElement(arr, element) {
return arr.includes(element) 
  //보다 더 쉬운 방법이 있지만,
  //Internet Explorer에서는 지원하지 않습니다
}

hasElement(words, 'Brown') // true
hasElement(words, 'nonexistent') // false

arr.includes(element)

array.join([separatorString]) -IMMUTABLE
element를 합쳐서 하나의 문자열로 만듦

let words = ['피', '땀', '눈물'];

words.join('') // '피땀눈물'
words.join(', ') // '피, 땀, 눈물'
words.join('+') // '피+땀+눈물'
words.join() // '피,땀,눈물'
profile
Let's code like chord !

0개의 댓글