FASTCAMPUS ST-FE 3기
Part 4. JavaScript Level up - Ch 1. JS 데이터
string
문자열의 생성자
리터럴 방식 "" '' ``
string객체에서 주어진 값과 일치하는 첫번째 인덱스를 반환.
띄어쓰기도 공백문자로서 값으로 인식한다.
const result = 'hello World'.indexOf('world'); //6
//string.prototype.indexOf();
//리터럴 방식으로 new prototype을 생성해준 형태.
일치값이 없을 땐 -1을 반환해준다.
const result = 'hello World'.indexOf('oching'); //-1
//string.prototype.indexOf();
이를 활용해 조건식 내 불린 데이터로 사용 가능하다.
const str = 'hello world';
console.log(str.indexOf('oching') !== -1) //false
문자열의 일부를 추출하면서 새로운 문자열을 반환한다.
첫째 인자에서부터 두번째 인자까지의 문자열을 잘라 반환한다.
주의할 점은 js가 0부터 numbering하기에 종료점 인덱스 그 직전까지 추출된다.
const str = 'hello world';
console.log(str.slice(0,3)) //hel
'world'를 출력해보려면?
const str = 'hello world';
console.log(str.slice(6,11)) //world
문자열을 교체해 새로운 문자열을 반환한다.
첫번째 인자를 두번째 인자의 문자열로 대체한다.
const str = 'hello world';
console.log(str.replace('world', 'oching')); //hello oching
문자열을 제거하는 데에도 활용할 수 있다.
const str = 'hello world';
console.log(str.replace('world', '')); //hello
정규식과 매치되는 부분을 검색한다.
정규표현식
(문자열에서 특정 문자 조합을 찾기 위한 패턴)을 활용해
str에 할당되어있는 이메일 주소에서 id에 해당되는 문자열만 반환하려한다.
const str = 'oching.choi@gmail.com';
console.log(str.match(/.+(?=@)/)[0]); //oching.choi
.match()는 배열의 형태로 값을 반환하기에 인덱스로 접근해 추출한다.
문자열 내의 공백을 없애준다.
공백은 하나의 공백문자로서 인식되기때문에 예를들어
사용자가 의도치않게 적은 공백까지 문자데이터로 인식하면
정확한 값을 얻어내기 어려울 수 있다.
.trim()은 공백을 없애주는 메서드로서 사용된다.
const str = ' hello world ';
console.log(str.trim()); //hello world
인자로 받는 숫자만큼 소숫점 아래 자리까지 반환한다.
const pi = 3.1459265358979;
console.log(pi); //3.14159265358979
const str = pi.toFixed(2);
console.log(str); //3.14
console.log(typeof str); //string
여기서 주의할 점은, 반환된 값의 타입이 숫자가 아닌,
문자열string이라는 점이다.
이를 다시 숫자타입으로 변환해주기 위해선
.parseInt()
인자의 문자열을 정수 숫자 데이터로 반환한다.
.parseFloat()
인자의 문자열을 실수 숫자 데이터로 반환한다.
const integer = parsInt(str);
const float = parseFloat(str);
console.log(integer) //3
console.log(float) //3.14
console.log(typeof integer, typeof float ) // number, number
수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장객체.
즉 자바스크립트에 이미 들어있는 메서드이며, 체인으로 연결해 쓸 수 있는 여러가지 수학적 계산객체들이 존재한다. 함수객체가 아니다.
MDN
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math
console.log('abs:' , Math.abs(-12)); //12
console.log('min:' , Math.min(2, 8)); //2
console.log('max:' , Math.max(2, 8)); //8
console.log('ceil:' , Math.ceil(3.14)); //4
console.log('floor:' , Math.floor(3.14)); //3
console.log('round:' , Math.round(3.14)); //3
console.log('random:' , Math.random()); //0.068686816174987663
Math.abs()
숫자의 절대값을 반환.
Math.min()
인수로 들어온 숫자데이터 중에 제일 작은 값을 반환.
Math.max()
인수로 들어온 숫자데이터 중에 제일 큰 값을 반환.
Math.ceil()
올림 처리한 값을 반환.
Math.floor()
내림 처리한 값을 반환.
Math.round()
반올림 처리한 값을 반환.
Math.random()
무작위 숫자 반환
리터럴로는 [] 로 표현되며 안에 값을 나열해준다.
나열된 값(인자)는 index라고 불리며
index의 값은 배열명[index순번]
으로 참조할 수 있다.
이렇게 참조하는 방법은 인덱싱이라고 한다.
js는 0부터 numbering하는 것에 유의해야한다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
console.log(number[1]); //2
console.log(fruits[2]); //cherry
MDN
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array
주어진 판별 함수(콜백함수를 인수로 갖는다)를 만족하는 첫번째 요소의 값을 반환.
해당되는 요소가 없다면 undefined를 반환한다.
한마디로, 인수로 콜백함수를 받고 콜백함수의 값이 true가 될 때 까지
배열을 상대로 콜백함수를 반복실행시킨다.
true가 되는 첫번째의 값을 찾아 반환하고
끝까지 true에 해당되는 값이 없다면 undefined를 반환하는 것이다.
const array1 = [5,12,8,130,44];
const found = array1.find(element => element > 10);
console.log(found); //12
배열의 인자 개수를 반환한다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
console.log(number.length); //4
console.log(fruits.length); //3
console.log([1,2].length); //2
배열이 빈 배열인지 확인해 불린 조건으로도 자주 활용된다.
console.log([].length); //0
두개의 배열 데이터를 병합해서 하나의 새로운 배열 데이터를 생성해 반환한다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
console.log(number.concat(fruits)); //4
console.log(number);
console.log(fruits);
원본의 데이터를 손상하지않고 새로운 배열을 생성한다.
데이터의 개수만큼 콜백함수를 반복 실행하는 함수.
매개변수를 세개로 받는 순서대로
element
인자값
index
해당인자의 순번. 0부터 numbering
array
콜백인 array 그대로 끌고와 구성. 선택사항이며 자주 쓰이지는 않는다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
//매개변수를 받는 순서
fruits.forEach(function(element, index, array){
console.log(element, index, array);
})
fruits.forEach(function(fruit, i){
console.log(fruit, i)
})
배열내의 모든 요소 각각에 대해 주어진 함수를 호출한 결과를 모아
다시 새로운 배열을 반환한다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const b = fruits.map(function(fruit,index){
return `${fruit}-${index}`
})
console.log(b);
이 특성을 이용해서 객체를 인수로 가진 배열을 만들어보자.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const b = fruits.map(function(fruit,index){
return { //객체생성 - 리터럴방식
id : index,
name : fruit
}
})
console.log(b);
💡 막간 복습) 위의 .map예제를 화살표함수로 바꿔보자
const number = [1,2,3,4]; const fruits = ['apple','banana','cherry']; const b = fruits.map((fruit,index) => ({ //객체생성 - 리터럴방식 id : index, name : fruit }) console.log(b);
배열안에 들어가 있는 인자중 특정 조건에
해당되는 인자만 필터링해 배열로 만들어준다.
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const b = number.filter(number => {
return number < 3
})
console.log(b);
정규식에 해당되는 인자를 반환
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const b = frunits.find(fruit => {
return /^b/.test(fruit); //정규식 : b로 시작하는 인자값
})
console.log(b); //banana
정규식에 해당되는 인자의 순번을 반환
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const b = frunits.findIndex(fruit => {
return /^b/.test(fruit); //정규식 : b로 시작하는 인자값
})
console.log(b); //1
인자로 받은 내용이 해당 배열에 인자에 존재하는 지 t/f의 불린 값으로 반환
const number = [1,2,3,4];
const fruits = ['apple','banana','cherry'];
const a = numbers.includes(2);
console.log(a); //true
원본수정됨!
인자값을 맨 뒤에 추가 , 인자값을 가장 앞 쪽에 추가
const number = [1,2,3,4];
number.push(5)
console.log(numbers) //[1,2,3,4,5]
number.unshift(5)
console.log(numbers) //[0,1,2,3,4,5]
원본수정됨!
인자의 순서 뒤집기
const number = [1,2,3,4];
number.reverse()
console.log(numbers) //[4,3,2,1]
원본수정됨!
첫번째 인수로 번째, 그 인수를 포함한 두번째 인수만큼 개수를 잡아
지우라는 뜻
const number = [1,2,3,4];
number.splice(2,1)
console.log(numbers) //[1,2,4]
특이하게 끼워넣는 것도 가능하다.
const number = [1,2,3,4];
number.splice(2,0, 999)
console.log(numbers) //[1,2,999,3,4]
리터럴로는 {}으로 표기된다.
다양한 키 모음 또는 더 복잡한 값들을 분류해 저장시킬 수 있다.
배열은 인자의 나열정도라면, 객체는 하나의 서랍장 처럼 key-value값 을 연결해
하나의 의미있는 인자값을 갖는다.
MDN
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object
첫번째 인자로 받은 target객체에 두번째 source객체를 병합한다.
인자의 key값이 같다면 두번째 객체의 value값으로 덧입혀진다.
💡 객체가 서로 같다? 의미를 자세히 파헤쳐보자
const userAge = { name : 'oching', age : 95 } const userEmail = { name : 'oching', email: 'oching.choi@gmail.com' } const target = Object.assign(userAge, userEmail); console.log(target); console.log(userAge); console.log(target == userAge); //true
동등비교연산자로 비교해보니 두 객체는 같다는 의미의 true가 출력된다.
값과 모양이 같으니까 같다는 뜻인걸까?
그럼 모양과 인자가 같은 객체는 모두 같은걸까?const a = {k:123} const b = {k:123} console.log(a===b) //false
위의 예시속 객체는 모양과 같은 인자를 갖는데도 불구, false값을 출력한다.
객체를 서로 비교해 같은 값인지 판별하는데 가장 중요한 요소는
해당 객체가 참조하고 있는 메모리 주소가 어디인지이다.
위의 경우 target과 userAge는 하나의 객체에 다른 객체를 병합시켜둔 형태이기에
둘은 같은 메모리 주소를 참조한다.
하지만 아래의 a,b에 할당된 각자의 객체는 서로 달리 선언된 별도의 객체이기에
각자만의 메모리 주소를 갖는다.
따라서 이 경우는 false값을 출력하는 것이다.
target객체의 자리에 빈 객체를 하나 생성해주면
source객체들을 병합한 하나의 새로운 객체도 만들수있다.
Object.assign({}, userAge, userEmail)
객체 안의 key값들만 모아 배열형태로 반환.
const userAge = {
name : 'oching',
age : 95,
email: 'oching.choi@gmail.com'
}
const keys = Object.keys(user);
console.log(keys); //['name', 'age', 'email']