Published
Edited
Jun 18, 2020
Insert cell
Insert cell
seasons = ["봄", "여름", "가을", "겨울"]
Insert cell
seasons.length // 배열 요소 개수 출력
Insert cell
{
for (let i = 0; i < seasons.length; ++i) // let인 이유? ++i로 i값이 계속 변하기 때문
console.log(i)
}
Insert cell
{ // ES6+
for (let i in seasons) // in은 0,1,2,3 인덱스 번호 콘솔창 출력
console.log(i)
}
Insert cell
{
for (let i = 0; i < seasons.length; ++i) // 인덱스 순으로 배열의 내용을 콘솔창 출력
console.log(seasons[i])
}
Insert cell
{ // ES6+
for (let v of seasons) // of는 바로 위에 것과 같이 인덱스 순으로 배열의 내용을 콘솔창 출력 더 간단히 작성할 수 있는 장점
console.log(v)
}
Insert cell
mixedArr = [1,"a","b",2,3,"c"] // 자바스크립트에서는 여러 개의 타입의 뒤섞인 배열을 만들 수 있다.
Insert cell
typeof mixedArr[0]
Insert cell
typeof mixedArr[1]
Insert cell
{ // 배열의 인덱스도 for (... in ..) 으로 얻어오면 숫자든 문자든 string 으로 취급된다
for (let i in mixedArr)
console.log(typeof i)
}
Insert cell
{
for (let v of mixedArr) // 순서대로 각각 배열의 요소마다 타입을 콘솔창에 출력해준다. 중복되는 것이 있으면 앞에 숫자로 표시해줌.
console.log(typeof v)
}
Insert cell
nums = [1,2,3]
Insert cell
chars = ["a","b","c"]
Insert cell
// nums.concat(chars) // 두개의 배열 객체를 새로운 배열 객체 생성
Insert cell
// chars.concat(nums) // 바로 위에 것과 반대로 새로운 배열 객체 생성
Insert cell
//nums.join() // () 괄호 안에 아무것도 없을 시 " , , " 이렇게 string 형태로 묶어서 출력
Insert cell
// nums.join('-') // 괄호 안에 '-' 가 있으므로 " - - " 형태로 출력
Insert cell
// nums.join(' - ') // 괄호 안에 ' - '가 있으므로 한칸 띄어쓰기를 해 " - - - " 형태로 출력
Insert cell
cs1 = ["a","b","c"]
Insert cell
cs1.push("d") // 기존의 cs1 변화, push()는 괄호 안에 요소가 1개이면 기존 배열 끝에 1개만 요소 추가하고 계속 실행하면 실행할 때마다 끝에 추가 됨.
Insert cell
cs1
Insert cell
ns1 = [1,2,3]
Insert cell
ns1.push(4,5) // 기존의 ns1 변화 push()는 괄호안에 1개만 쓰면 1개만 추가 되고 여러개 작성하면 끝에 여러개가 추가 된다.
Insert cell
ns1
Insert cell
{ // Array의 push, pop 메소드로 (배열 맨 끝에) - 기존배열 변함
let arr = [1,2,3,4]
console.log(arr) // [1,2,3,4]
arr.push(5,6,7)
console.log(arr) // [1,2,3,4,5,6,7]
arr.pop() // pop()은 괄호 안에 숫자에 상관없이 호출이 되면 무조건 배열의 오른쪽 마지막 요소부터 1개씩 지운다.
console.log(arr) // [1,2,3,4,5,6]
arr.pop()
console.log(arr) // [1,2,3,4,5]
arr.pop()
console.log(arr)// [1,2,3,4]
}
Insert cell
{ // Array의 unshift, shift 메소드 (배열 맨 앞에) - 기존배열 변함
let arr = ["a","b","c"]
console.log(arr) // ["a","b","c"]
arr.shift() // 맨 앞에서 하나를 빼온다
console.log(arr) // ["b","c"]
arr.unshift("z") // 맨 앞에 집어넣는다
console.log(arr) // ["z","b","c"]
arr.unshift("x","y") // 맨 앞에 집어넣는다 unshift()는 괄호 안에 여러 개 작성하면 여러 개 추가 가능.
console.log(arr) // ["x","y","z","b","c"]
}
Insert cell
{ // Array의 splice 메소드 (원하는 위치에 삭제/추가) 기존 배열이 변한다. - 인자 1개일 때
let numbers = [0,1,2,3,4,5]
console.log( numbers ) // [0,1,2,3,4,5]
let ns = numbers.splice(2) // 인덱스 2부터 (세번째 요소부터) 배열의 끝까지 빼내옴
console.log( ns ) // [2,3,4,5]
console.log( numbers ) // [0,1]
}
Insert cell
{ // Array의 splice 메소드 (원하는 위치에 삭제/추가) - 인자 2개일 때
let chars = ["a","b","c","d","e","f"]
console.log( chars )
let cs = chars.splice(2,3) // 인덱스 2부터 (세번째 요소부터) 3개를 빼내옴
console.log( cs )
console.log( chars )
}
Insert cell
{ // Array의 splice 메소드 (원하는 위치에 삭제/추가) - 인자 3개일 이상일 때
let chars = ["a","b","c","d","e","f"]
console.log( chars )
// 인덱스 2부터 (세번째 요소부터) 3개를 빼내오고, 그 자리에 "x","y"를 추가해줌
let cs = chars.splice(2,3,"x","y")
console.log( cs )
console.log( chars )
}
Insert cell
{ // Array의 slice 메소드 - 원하는 위치에서 가져오지만 원래 배열을 변화 없음
let chars = ["a","b","c","d","e","f"]
console.log( chars )
let cs = chars.slice(2) // 인덱스 2부터 (세번째 요소부터) 끝까지 복사해옴
console.log( cs )
console.log( chars )
}
Insert cell
{ // Array의 slice 메소드 - 원하는 위치에서 가져오지만 원래 배열을 변화 없음
let chars = ["a","b","c","d","e","f"]
console.log( chars )
let cs = chars.slice(2,5) // 인덱스 2부터 5직전까지 (세번째에서 다섯번째 요소까지) 복사해옴
console.log( cs )
console.log( chars )
}
Insert cell
{ // Array의 sort 메소드
let ns = [2,5,1,3,4]
ns.sort()
console.log( ns )
}
Insert cell
{ // Array의 sort 메소드 - compareFunction 활용 (기본동작 오름차순)
/*
let ns = [2,5,1,3,4]
ns.sort( function(a,b) {
(a===b)? 0: (a<b)? -1: 1
})
return ns ES6+ 전까지는 이렇게 작성*/
// ES6+부터는 이렇게 작성
let ns = [2,5,1,3,4]
return ns.sort( (a,b) => (a===b)? 0: (a<b)? -1: 1 )
console.log(ns)
//return ns
}
Insert cell
{ // Array의 sort 메소드 - compareFunction 활용 (내림차순)
let ns = [2,5,1,3,4]
ns.sort( (a,b) => (a===b)? 0: (a>b)? -1: 1 )
console.log(ns)
//return ns
}
Insert cell
{ // Array의 every 메소드 - 어떤 성질을 검사하는 함수를 받아서 배열의 모든 요소가 그 성질을 만족하는지
let ns = [2,4,6,8,10]
let even = x => x % 2 === 0 // 이 조건에 하나라도 맞지 않으면 false가 나온다.
return ns.every( even )
// return [even(2), even(4), even(6), even(8), even(10)] // Array(5) [true, true, true, true, true] 출력
}
Insert cell
{ // Array의 filter 메소드 - 어떤 성질을 검사하는 함수를 받아서 만족하는 요소만 골라서 새로운 배열을 만든다
let ns = [1,2,3,4,5,6,7,8,9,10]
let even = x => x%2 === 0 // 원래의 배열 ns는 가만히 두고 이 조건에 만족하는 요소만 골라서 새로운 배열을 만든다.
return ns.filter( even )
}
Insert cell
{ // Array의 forEach 메소드 - 함수를 받아서 각각의 모든 요소를 인자로 넘겨서 호출
let cs = ["a","b","c","d","e"]
cs.forEach( x => console.log(x) ) // 모든요소에 접근해서 a , b , c ..하나씩 출력해줌
}
Insert cell
{ // Array의 map 메소드 - 함수를 받아서 모든 요소를 인자로 호출한 결과값을 모은 새로운 배열을 만든다
let ns = [1,2,3,4,5]
return ns.map( x => x*x )
} // map은 forEach와 비슷하다. map은 기존 배열은 가만히두고 x*x와 같은 새로운 결과값을 모아 새로운 배열을 만들지만, forEach는 아무것도 데이터를 만들어 내지 않고 각각 함수호출하고 실행하고 결과값을 생성하지 않는다.
Insert cell
{ // Array의 reverse 메소드 - 배열의 순서를 반대로
let cs = ["a","b","c","d","e"]
cs.reverse()
return cs
}
Insert cell
Insert cell
Insert cell
{ // 강의 영상 관련 과제 첫번째 문제 - 이름(name)을 기준으로 가나다순으로 정렬 (3점)
let persons = [ {name:"홍길동", age:45}, {name:"김연아", age:30}, {name:"이순신", age:54} ]
persons.sort((a,b) => (a.name === b.name) ? 0 : (a.name < b.name) ? -1: 1)
console.log(persons)
/* return persons.sort(function(a,b) {
return (a.name === b.name) ? 0 : (a.name < b.name) ? -1:1
}) */
}

Insert cell
{ // 강의 영상 관련 과제 두번째 문제 - 나이(age)를 기준으로 오름차순으로 정렬 (3점)
let persons = [ {name:"홍길동", age:45}, {name:"김연아", age:30}, {name:"이순신", age:54} ]

return persons.sort((a,b) => (a.age === b.age) ? 0 : (a.age < b.age) ? -1: 1 )
/* return persons.sort(function(a,b) {
return (a.age === b.age) ? 0 : (a.age < b.age) ? -1:1
}) */
}
Insert cell
Insert cell
[1,2,3,4].reduce( (x,y) => x+y ) // 연산하는 함수만 넘길 때
Insert cell
[].reduce( (x,y) => x+y ) // 연산하는 함수만 넘겼을 때는 초기값이 없기 때문에 원소가 없는 빈 배열에 대해서는 에러
Insert cell
[].reduce( (x,y) => x+y, 0) // 빈 배열에 대해서도 동작하게 하려면 시작값을 지정
Insert cell
[1,2,3,4].reduce( (x,y) => x+y, 10000 ) // 연산자 함수와 초기값을 넘길 때
Insert cell
[1,2,3,4].reduce( (x,y) => x*y ) // 곱셈을 예로 연습해 봅시다
Insert cell
[].reduce( (x,y) => x*y ) // 연산하는 함수만 넘겼을 때는 초기값이 없기 때문에 원소가 없는 빈 배열에 대해서는 에러
Insert cell
[].reduce( (x,y) => x*y, 1 ) // 빈 배열에 대해서도 동작하게 하려면 시작값을 지정
Insert cell
[1,2,3,4].reduce( (x,y) => x*y, 1 )
Insert cell
[1,2,3,4].reduce( (x,y) => x*y, 100 )
Insert cell
Insert cell
[].join() // join은 reduce와 다르게 빈리스트에서도 오류나지 않고 출력해줌
Insert cell
["a","b","c"].join()
Insert cell
[].reduce((x,y) => x+","+y) // 빈리스트이므로 에러 빈리스트 때와 아닐 때를 구분하는 조건문 추가
Insert cell
["a","b","c"].reduce( (x,y) => x+","+y )
Insert cell
// join과 같은 일을 하는 함수를 내가 직접 reduce를 이용해서 짠다
myjoin = (arr) => (arr.length===0)? "": arr.reduce( (x,y)=>x+","+y )
Insert cell
myjoin( [1,2,3,4] )
Insert cell
myjoin( [] )
Insert cell
Insert cell
myarr = ["x1","x2","x3","x4"]
Insert cell
op = (x,y) => "("+x+"⚝"+y+")" // 가운데에 별표모양을 써주고 괄호안에 넣어주는 연산자
Insert cell
op("z1","z2")
Insert cell
flip = (op) => (x,y) => op(y,x) // 고차함수(higher-order function) 정의
Insert cell
op2 = flip(op)
Insert cell
op2("z1","z2")
Insert cell
myarr
Insert cell
// Array의 reduce 메소드 (foldl에 해당)
myarr.reduce(op,"v0") // v0는 초기값 초기값을 기준으로 배열원소를 왼쪽으로 괄호를 감싸 오른쪽으로 처리해러 foldl 해당
Insert cell
[1,2,3,4].reduce( (x,y) => x-y, 100 ) // ((((100-1)-2)-3)-4)
Insert cell
// Array의 reduceRight 메소드 (foldr에 정확히 해당하지는 않음)
myarr.reduceRight(op,"v0")
Insert cell
// reduceRight은 뒤집어준 다음에 reduce를 하는 것과 같다
myarr.map( x => x ).reverse().reduce(op,"v0") // reduceRight 과 같다
//map에서 map을 쓰고 reverse하는 이유는 map을 써야 기본 배열은 바뀌지 않고 reverse 할 수 있기 때문이다.
Insert cell
// Array의 reduceRight 메소드를 foldr에 해당하게 하려면
myarr.reduceRight(flip(op),"v0")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more