17-18일차 JavaScript Data(1)

변승훈·2022년 4월 20일
0

JavaScript의 Data(1)

1. String

String 전역 객체는 문자열(문자의 나열)의 생성자 이다.

indexOf() 메소드

indexOf(searchValue)메소드는 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다. 일치하는 값이 없다면 -1을 반환한다.

매개변수(searchValue) : 찾으려는 문자열, 아무 값도 주어지지 않으면 문자열 "undefined"를 찾으려는 문자열로 사용한다.

indexOf()를 활용하여 boolean을 확인할 수도 있다.

// String.prototype.indexOf()
let result = 'Hello world!'.indexOf('world');
console.log(result);  // 6, 첫 번째 등장 인덱스
result = 'Hello world!'.indexOf('Hun');
console.log(result); //  -1, 찾을 수 없으면 -1 반환

// indexOf()를 활용한 boolean 확인 방법 예시
const str = 'Hello world!';
console.log(str.indexOf('Hun') !== -1);

length

글자(문자)의 개수를 알아내고 싶을 때 사용한다.

const str = '0123';
console.log(str.length);    // 4
console.log('01 23'.length); // 5, 띄어쓰기도 포함

slice()

slice(beginIndex, endIndex)메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환한다.
beginIndex는 문자열의 시작, endIndex는 문자열의 끝을 의미하며 ★endIndex는 그 직전까지만을 추출한다!

const str = 'Hello world!';
console.log(str.slice(0, 3));   // Hel, (beginIndex, endIndex), endIndex는 그 ★직전까지 추출
console.log(str.slice(6, 11));  // world

replace()

replace(firstArgument, secondArgument) 메소드는 문자데이터에서 첫 번째 인수에 해당하는 문자를 찾아서 두 번째 인수에 해당하는 문자로 교체를 해주는 메소드이다.

const str = 'Hello world!';
console.log(str.replace('world', 'Hun')); // Hello Hun!, 첫 번째 인수를 두 번째 인수로 교체해준다.
console.log(str.replace(' world!', ''));  // Hello, 지우고 싶을때도 사용이 가능하다.

match()

match() 메소드는 특정한 문자 데이터에서 정규표현식을 통해 특정한 문자를 일치시켜 그것을 배열 데이터로 반환하여 원하는 정보를 item으로 추출해서 사용을 한다.

const str = 'rk645046@gamil.com'; 
console.log(str.match(/.+(?=@)/));  // 정규 표현식 사용, ["rk645046", index:0, input:"rk645046@gmail.com", groups: undefined]
console.log(str.match(/.+(?=@)/)[0]); // rk645046

trim()

trim()메소드는 특정한 문자 데이터의 앞, 뒤 모든 공백문자를 제거해주는 메소드이다.

const str = '     Hello world  ';
console.log(str); //     Hello world  
console.log(str.trim()); // Hello world, 공백 제거

2. 숫자와 수학

javascript에서 숫자가 어떻게 쓰이는지 예시를 통해 알아보자.

// 숫자와 수학
const pi = 3.14159265358979;
console.log(pi);  // 3.14159265358979

toFixed()

toFixed(value) 메소드는 숫자 데이터에 사용할 수 있는 메소드이다.
메소드 호출 시 인수로 소숫점 몇 번째 자리 까지 유지할 것인지 명시를해준다.
toFixed() 사용 시 문자 데이터로 반환이 된다!

const str = pi.toFixed(2);  // 3.14, 숫자에서만 사용할 수 있는 메소드, 소수점 두 자리 까지 반환

console.log(str);
console.log(typeof str);  // string

parseInt(), parseFloat()

parseInt(), parseFloat()는 전역함수(전체의 영역에서 언제든지 사용할 수 있는 함수)이며 각각 정수와 실수 부분을 반환하며 숫자 데이터로 반환이 된다!

// 전역함수
const integer = parseInt(str);  // 정수, 정수 부분을 반환, 숫자로 변환
const float = parseFloat(str);  // 실수, 실수 부분을 반환, 숫자로 변환
console.log(integer); // 3,  정수만 반환
console.log(float);   // 3.14, 실수로 반환
console.log(typeof integer, typeof float);  // number number

Math 함수들

Math는 수학적인 상수와 함수를 위한 속성과 메소드를 가진 내장 객체이며 함수 객체가 아니다!

Math.abs(): 절대값을 반환한다.
Math.min(): 입력 받은 수 중 최소 값을 반환한다.
Math.max(): 입력 받은 수 중 최대 값을 반환한다.
Math.ceil(): 소수점 올림 처리를 하여 반환한다.
Math.floor(): 소수점 내림 처리를 하여 반환한다.
Math.round(): 소수점 반올림 처리를 하여 반환한다.
Math.random(): 0 ~ 1 사이의 숫자를 무작위로 반환한다(난수).

// 다른 메소드들
console.log('abs : ', Math.abs(-12));       // abc : 12, 절대 값
console.log('min : ', Math.min(2, 8));      // min : 2, 입력받은 수 중 최소 값
console.log('max : ', Math.max(2, 8));      // max : 8, 입력받은 수 중 최대 값
console.log('ceil : ', Math.ceil(3.14));    // ceil : 4, 올림
console.log('floor : ', Math.floor(3.14));  // floor: 3, 내림
console.log('round : ', Math.round(3.14));  // round: 3, 반올림
console.log('random : ', Math.random());    // random : 0.194961321, 0 ~ 1 사이의 숫자를 무작위로 반환(난수)


// 0 ~ 9 사이를 출력하는 함수로 만들어 보기 
function random() {
  Math.floor(Math.random() * 10);
}
random(); 

3. 배열

배열은 다음과 같은 형태를 나타낸다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];
  • index: 배열 데이터 내부에 들어있는 특정 데이터의 위치를 가르키는 숫자이다. zero-based에 따라 0부터 시작한다.
  • indexing: 인덱스에 숫자를 넣어 조회하는 것을 의미한다.
  • element, item(요소): 배열 데이터 내부에 들어있는 각각의 데이터를 의미한다.

원하는 값을 조회하는 방법은 다음 예시와 위의 개념을 보고 이해해 보자.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

console.log(numbers[1]);  // 2
console.log(fruits[2]);   // Cherry

.length

.length 메소드는 해당 배열의 길이를 알 수 있다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

console.log(numbers.length);  // 4
console.log(fruits.length);   // 3
console.log([1, 2].length);   // 2

console.log([].length);  // 0 

.concat()

.concat() 메소드는 원본의 배열 데이터에 영향이 없고 새로운 배열 데이터가 합쳐져서 만들어진다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

console.log(numbers.concat(fruits));  // [1, 2, 3, 4, Apple', 'Banana', 'Cherry'];
console.log(numbers);   // [1, 2, 3, 4]
console.log(fruits);   // ['Apple', 'Banana', 'Cherry']

.forEach()

.forEach() 메소드는 배열데이터의 아이템 갯수만큼 인수로 사용된 callback함수가 반복적으로 실행된다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

fruits.forEach(function (element, index, array) { //element대신 item도 가능, fruit도 가능, 자유롭게 작성 가능, array는 잘 사용하지 않는다.
  console.log(element, index, array); 
  //  Apple 0 ['Apple', 'Banana', 'Cherry']
  //  Banana 1 ['Apple', 'Banana', 'Cherry']
  //  Cherry 2 ['Apple', 'Banana', 'Cherry']
});

.map()

.map() 메소드는 callback에서 반환된 특정한 데이터를 기준으로 해서 데이터들의 새로운 배열을 반환해준다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

// fotEach()를 이용한 새로운 배열 반환
// 1. 일반적인 함수 표현식
// const a = fruits.forEach(function (fruit, index) {
// 2. 화살표 함수 표현식
const map = fruits.forEach((fruit, index) => {	
  console.log(`${fruit}-${index}`)
  // Apple-0
  // Banana-1
  // Cherry-2
})
console.log(map); // undefined

// map()을 이용한 방식
// 1. 일반적인 함수 표현 방식
// const b = fruits.map(function (fruit, index) {

// return `${fruit}-${index}`;

// 2. 객체 리터럴 방식으로 작성
// return {
  //   id : index,
  //   name : fruit
  // };
// }

// 3. 화살표 함수로 변형
  const mapArrow = fruits.map((fruit, index) =>({
      id : index,
      name : fruit
  }) 
);
console.log(mapArrow); 
// 1. ["Apple-0", "Banana-1", "Cherry-2"], 2.[{id: 0, name: "Apple"},{id:1, name: "Banana"},{id:2, name: "Cherry"}}]

.filter() :

.filter() 메소드는 배열데이터 안에 들어있는 각각의 item들을 특정한 기준으로 필터링한다. 새로운 배열을 반환해준다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

// map()을 사용한 방법
const mapVsFilter = numbers.map(number => {
  return number < 3; 
})
// 간결한 함수 버전
// const mapVsFilter = numbers.map(number => number < 3 );
console.log(mapVsFilter); // [true, true, false, false]

// filter()를 사용한 방법
const filter = numbers.filter(number => {
  return number < 3;
})  
// 간결한 함수 버전
// const filter = numbers.filter(number => number < 3 );
console.log(filter); // [1, 2]

.find()

.find() 메소드는 배열데이터 안에서 조건에 맞는 특정한 item을 찾을때 사용한다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

const find = fruits.find(fruit => {
  return /^B/.test(fruit);  // /^B/대문자 B로 시작하는 문자 데이터
})
// 간결한 함수 버전
// const find = fruits.find(fruit => /^B/.test(fruit));
console.log(find);

.findIndex()

.findIndex() 메소드는 배열데이터 안에서 조건에 맞는 특정한 item의 index를 반환한다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

const findIndex = fruits.find(fruit => {
  return /^B/.test(fruit);  // /^B/대문자 B로 시작하는 문자 데이터
})
// 간결한 함수 버전
// const findIndex = fruits.findIndex(fruit => /^B/.test(fruit));
console.log(findIndex);

.includes()

.includes() 메소드는 배열데이터 부분에 인수로 사용된 특정한 데이터가 포함되어 있는지 확인한다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

const includes1 = numbers.includes(3);
console.log(includes1); // true
const includes2 = numbers.includes('HUN');
console.log(includes2); // false

여기서 부터는 원본 데이터가 수정될 수 있다.

.push()

.push() 메소드는 배열데이터 가장 뒤쪽부분에 데이터가 삽입되어진다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

numbers.push(5);
console.log(numbers);  // [1, 2, 3, 4, 5]

.unshift()

.unshift() 메소드는 배열데이터 가장 앞부분에 데이터가 삽입되어진다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

numbers.unshift(0);
console.log(numbers);  // [0, 1, 2, 3, 4]

.reverse()

.reverse() 메소드는 배열의 item의 순서를 뒤집어내는 용도로 사용한다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

numbers.reverse();
fruits.reverse();

console.log(numbers); //  [4, 3, 2, 1]
console.log(fruits);  //  ["Cheery", "Banana", "Apple"]

.splice()

.splice(index, 개수, 끼워넣을 값) 메소드는 배열데이터에서 특정한 item들을 지울때 사용한다.
새로운 item을 끼워넣는 메소드로 사용하기도 한다.

const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];


numbers.splice(2, 0, 999); //  [1, 2, 999, 3, 4] 
numbers.splice(2, 1, 99); // [1, 2, 99, 4] 
numbers.splice(2, 1); // [1, 2, 4]
fruits.splice(2, 0, "Orange");  // ["Apple", "Banana", "Orange", "Cheery"]
console.log(fruits);
profile
잘 할 수 있는 개발자가 되기 위하여

0개의 댓글