connecting dots

JS 데이터 | 문자 (String. ~), 숫자 (Math. ~), 배열(Array. ~) 본문

Online Class/DevCamp

JS 데이터 | 문자 (String. ~), 숫자 (Math. ~), 배열(Array. ~)

dearsuhyun 2024. 6. 13. 00:15

1. 문자

String.prototype.indexOf()

indexOf() 메서드는 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다.

일치하는 값이 없으면 -1을 반환합니다.

 

매개변수

searchValue

찾으려는 문자열.

아무 값도 주어지지 않으면 문자열 "undefined"를 찾으려는 문자열로 사용합니다.

 

반환 값

searchValue의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.

 

const result = 'hello world!'.indexOf('heropy')

console.log(result)
// -1

 

.length

const str = '0123'

console.log(str.length) // 4
console.log('0123'.length) // 4
const str = 'hello world!'
console.log(str.indexOf('world!')) // 6
const str = 'hello world!'
console.log(str.indexOf('heropy') !== -1)
// false
// heropy가 없으니까 -1나오는데 '!=='이니까 false

 

String.prototype.slice()

slice() 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.

const str = 'hello world!'

console.log(str.slice(0, 3)) // hel (0이상 3미만)

 

매개변수

beginIndex

추출 시작점인 0부터 시작하는 인덱스입니다. 만약 음수라면, beginIndex는 strLength(문자열 길이) + beginIndex로 취급됩니다. (예를 들어 beginIndex가 -3이면 시작점은 strLength - 3).

만약 beginIndex가 strLength 보다 크거나 같은 경우, slice()는 빈 문자열을 반환합니다.

 

endIndex Optional

0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됩니다. 인덱스 위치의 문자는 추출에 포함되지 않습니다.

만약 endIndex가 생략된다면, slice()는 문자열 마지막까지 추출합니다.

만약 음수라면, endIndex는 strLength(문자열 길이) + endIndex 로 취급됩니다(예를 들어 endIndex가 -3이면 종료점은 strLength - 3).

const str = 'hello world!'

console.log(str.slice(6, 11))
// world

 

String.prototype.replace()

String 값의 replace() 메서드는 pattern의 단일, 일부 혹은 모든 일치 항목이 replacement로 대치된 새로운 문자열을 반환합니다. 

pattern은 문자열 혹은 RegExp일 수 있습니다.

replacement는 문자열이나 각 일치 항목마다 호출되는 함수일 수 있습니다.

만약 pattern이 문자열이라면, 오직 첫 번째 항목만 변경됩니다. 원본 문자열은 변하지 않습니다.

 

replace(바꾸고 싶은 것, 그 자리로 들어갈 것)

const str = 'hello world!'

console.log(str.replace('world', 'heropy'))
// hello heropy!
const str = 'hello world!'

console.log(str.replace(' world!', ''))
//hello

 

String.prototype.match()

match() 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.

                                            ▶ .+(?=@)

const str = 'thesecon@gmail.com'
console.log(str.match(/.+(?=@)/))

//['thesecon', index: 0, input: 'thesecon@gmai.com', groups: undefined]

const str = 'thesecon@gmai.com'
console.log(str.match(/.+(?=@)/)[0]) // @앞에 아이디를 출력해주세요
//thesecon

 

String.prototype.trim()

trim() 메서드는 문자열 양 끝의 공백을 제거하고 원본 문자열을 수정하지 않고 새로운 문자열을 반환합니다. 여기서 말하는 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.

한쪽 끝의 공백만 제거한 새로운 문자열을 반환하려면

trimStart() 또는 trimEnd()를 사용하세요.

const str = '     hello world   '

console.log(str.trim())
//hello world

 

.toFixed

메소드가 호출될 때 인수로 소수점의 몇 번째 자리까지 유지할 것인지를 명시

const pi = 3.14159265358979
console.log(pi)

const str = pi.toFixed(2)
console.log(str) //3.14
console.log(typeof str) //string

 

parseInt / parseFloat

const integer = parseInt(str) // 숫자가 들어있는 문자데이터를 넣으면 정수로 반환, 3
const float = parseFloat(str) // 소수점 자리 유지하면서 문자데이터를 숫자로 변환해줌
console.log(integer) // 3
console.log(float) // 3.14
console.log(typeof interger, typeof float) // number, number

 

 

2. 숫자

Math

Math 는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다. 함수 객체가 아닙니다.

### 1. **Math는 내장 객체입니다.**
   - 자바스크립트에서 `Math`는 특별한 객체입니다. 이미 자바스크립트에 내장되어 있어서 우리가 별도로 만들 필요가 없습니다.
   - 이 객체는 다양한 수학적인 계산을 도와주는 속성(상수)과 메서드(함수)를 가지고 있습니다.

### 2. **수학적인 상수와 함수**
   - `Math` 객체에는 다양한 수학적인 상수와 함수가 포함되어 있습니다.
   - 예를 들어:
     - 상수: `Math.PI` (원주율 3.14159...)
     - 함수: `Math.sqrt()` (제곱근을 계산하는 함수)

### 3. **Math는 함수 객체가 아닙니다.**
   - `Math` 자체는 함수가 아니기 때문에 `Math()`처럼 호출할 수 없습니다.
   - 대신, `Math`는 그 안에 있는 여러 함수를 제공하는 "도구 상자" 같은 역할을 합니다.
   - 예를 들어, `Math.sqrt(9)`라고 하면 `Math` 객체 안에 있는 `sqrt`라는 함수를 호출해서 9의 제곱근을 구하는 것입니다.

### 요약
- **Math는 내장 객체다**: 이미 자바스크립트에 포함되어 있고, 우리가 만들 필요가 없다.
- **수학적인 상수와 함수**: 다양한 수학적인 상수(예: `Math.PI`)와 함수(예: `Math.sqrt()`)를 제공한다.
- **함수 객체가 아니다**: `Math` 자체는 호출할 수 없지만, 그 안에 있는 함수를 호출할 수 있다.

 

Math.abs()

Math.abs() 함수는 주어진 숫자의 절대값을 반환합니다. 

x가 양수이거나 0이라면 x를 리턴하고, x가 음수라면 x의 반대값, 즉 양수를 반환합니다.

function difference(a, b) {
  return Math.abs(a - b);
}

console.log(difference(3, 5));
// Expected output: 2

console.log(difference(5, 3));
// Expected output: 2

console.log(difference(1.23456, 7.89012));
// Expected output: 6.6555599999999995

 

Math.min

인수로 들어온 숫자 데이터 중 가장 작은 데이터를 확인해주는 것

Math.max

가장 큰 데이터를 반환하는 것

Math.ceil

올림 처리를 하는 것

Math.floor

내림 처리를 하는 것

Math.round

반올림

Math.random

0에서 1 까지의 무작위의 숫자 출력

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.324482

 

 

3. 배열 Array

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

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

 

Array.prototype.find()

Array 인스턴스의 find() 메서드는 제공된 배열에서 제공된 테스트 함수를 만족하는 첫 번째 요소를 반환합니다.

테스트 함수를 만족하는 값이 없으면 undefined가 반환됩니다.

 

매개변수

callback배열의 각 요소에 대해 실행할 함수입니다. 일치하는 요소를 찾았으면  값을 반환하고, 그렇지 않으면 거짓 값을 반환해야 합니다.

함수는 다음 인수를 사용하여 호출됩니다.

element 배열에서 현재 처리되고 있는 요소.

index 배열에서 현재 처리되고 있는 요소의 인덱스.

[array] (find()가 호출된 배열.

 

반환 값

제공된 테스트 함수를 만족하는 배열의 첫 번째 요소입니다. 테스트 함수를 만족하는 요소가 없으면, undefined가 반환됩니다.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element) => element > 10);

console.log(found);
// Expected output: 12

 

Array.prototype.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

 

Array.prototype.concat()

두 개의 배열 데이터를 병합해서 새로운 배열 데이터를 반환해주는 메소드

원본의 데이터는 손상되지 않음

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

console.log(numbers.concat(fruits))
// (7) [1, 2, 3, 4, 'apple', 'banana', 'cherry']
console.log(numbers)
// (4) [1, 2, 3, 4]
console.log(fruits)
// (3) ['apple', 'banana', 'cherry']

 

Array.prototype.forEach()

forEach()가 붙어있는 배열 데이터의 아이템 개수만큼 인수로 사용된 콜백함수가 반복적으로 실행됨

실행될 때 마다 index의 값이 0부터 하나씩 증가함

콜백에 해당하는, forEach()가 붙어있는 그 배열을 말함

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

fruits.forEach(function (element, index, array) {
  console.log(element, index, array)
})

// apple 0 (3) ['apple', 'banana', 'cherry']
// banana 1 (3) ['apple', 'banana', 'cherry']
// cherry 2 (3) ['apple', 'banana', 'cherry']

// 매개변수 이름은 아무거나(fruit, item 등)
// index는 i라고 쓰기도 함

 

Array.prototype.map()

인수로 사용하는 콜백의 내부에서 반환하는 데이터를 가지고 그 데이터들을 모아놓은 새로운 배열을 만들어서 반환해줌

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.forEach(function (fruit, index) {
  console.log(`${fruit}-${index}`)
})
console.log(a)

// apple-0
// banana-1
// cherry-2

const b = fruits.map(function (fruit, index) {
  return `${fruit}-${index}`
})
console.log(b)

// ['apple-0', 'banana-1', 'cherry-2']

 

const b = fruits.map(function (fruit, index) {
  return {
    id: index,
    name: fruit
  }
  //객체 리터럴 방식
})
console.log(b)

 

화살표 함수

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.forEach((fruit, index) => {
  console.log(`${fruit}-${index}`)
})
console.log(a)

const b = fruits.map((fruit, index) => ({
  id: index,
  name: fruit
}))
console.log(b)
apple-0
banana-1
cherry-2

undefined

[
  { id: 0, name: 'apple' },
  { id: 1, name: 'banana' },
  { id: 2, name: 'cherry' }
]
`undefined`가 되는 이유는 `forEach` 메서드 자체의 동작 방식 때문입니다. 이를 쉽게 설명해드릴게요.

### 1. `forEach`와 `map`의 차이

#### `forEach` 메서드
- **역할**: 배열의 각 요소에 대해 주어진 함수를 실행합니다.
- **반환 값**: 항상 `undefined`를 반환합니다. 즉, 배열의 각 요소에 대해 어떤 작업을 수행할 때 사용되며, 이 작업의 결과를 반환하지 않습니다.
- **예시**:
  ```javascript
  const fruits = ['apple', 'banana', 'cherry'];

  const a = fruits.forEach((fruit, index) => {
    console.log(`${fruit}-${index}`);
  });
  console.log(a);  // undefined
  ```

  - 여기서 `forEach`는 각 과일과 인덱스를 출력하는 작업을 수행합니다.
  - 하지만 `forEach` 메서드 자체는 항상 `undefined`를 반환합니다.

#### `map` 메서드
- **역할**: 배열의 각 요소에 대해 주어진 함수를 실행하고, 그 결과를 모아 새로운 배열을 반환합니다.
- **반환 값**: 새로운 배열을 반환합니다. 이 배열은 원래 배열의 각 요소에 주어진 함수가 적용된 결과로 구성됩니다.
- **예시**:
  ```javascript
  const fruits = ['apple', 'banana', 'cherry'];

  const b = fruits.map((fruit, index) => ({
    id: index,
    name: fruit
  }));
  console.log(b);
  ```

  - 여기서 `map`은 각 과일과 인덱스를 사용하여 `{ id, name }` 객체를 만들고, 이 객체들로 이루어진 새로운 배열을 반환합니다.

### 화살표 함수와 관계

화살표 함수는 함수 표현의 한 방식일 뿐, `forEach`나 `map`의 동작 방식에는 영향을 주지 않습니다. 

- **화살표 함수 사용**: 
  ```javascript
  fruits.forEach((fruit, index) => {
    console.log(`${fruit}-${index}`);
  });
  ```
  - 여기서 화살표 함수는 각 요소에 대해 실행될 함수의 표현 방식입니다. `forEach` 메서드는 화살표 함수든 일반 함수든 항상 `undefined`를 반환합니다.

### 요약
- `forEach`는 배열의 각 요소에 대해 주어진 함수를 실행하고 `undefined`를 반환합니다.
- `map`은 배열의 각 요소에 대해 주어진 함수를 실행하고 새로운 배열을 반환합니다.
- 화살표 함수는 그저 함수 표현 방식일 뿐, `forEach`가 `undefined`를 반환하는 이유와는 관련이 없습니다. 
`forEach`는 원래 반환값이 `undefined`인 메서드입니다.

 

Array.prototype.filter()

배열 데이터 안의 각각의 아이템들을 특정한 기준에 따라 필터링 —> 필터된 새로운 배열 데이터를 반환함

원본 데이터 영향 없음

const numbers = [1, 2, 3, 4]
const fruits = ['apple', 'banana', 'cherry']

const a = numbers.map(number => {
  return number < 3
})
console.log(a) // [true, true, false, false]

const b = numbers.filter(number => {
  return number < 3
})
console.log(b) // [1, 2]

 

map 메서드가 반환하는 배열은 원래 배열의 각 요소에 주어진 함수가 적용된 결과를 포함합니다.
이 경우, 함수는 각 숫자가 3보다 작은지를 평가하여 true 또는 false를 반환하기 때문에, 결과 배열도 불린 값으로 구성됩니다.


filter 메서드는 주어진 함수의 조건을 만족하는 요소들만 포함된 새로운 배열을 반환합니다. 따라서, 결과 배열은 [1, 2]가 됩니다.

 

화살표 함수 ver

const a = numbers.map(number => number < 3)
console.log(a)

const b = numbers.filter(number => number < 3)
console.log(b)

 

Array.prototype.find()

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

const a = fruits.find(fruit => {
  return /^B/.test(fruit)
  // 정규표현식, B로 시작하는 문자데이터
})
console.log(a) // Banana
const a = fruits.find(fruit => /^B/.test(fruit))
console.log(a)
정규표현식 설명
/^B/

/로 둘러싸인 부분이 정규표현식입니다.
^는 문자열의 시작을 의미합니다.
B는 대문자 B를 의미합니다.

따라서 /^B/는 “문자열의 시작이 B로 시작하는지”를 확인하는 정규표현식입니다.
동작 방식

1. find 메서드는 배열의 각 요소에 대해 주어진 함수를 실행합니다.
2. 함수는 정규표현식 /^B/를 사용하여 각 과일 이름이 B로 시작하는지 확인합니다.
3. test 메서드는 각 과일 이름을 검사하여 true 또는 false를 반환합니다.
4. find 메서드는 조건을 만족하는 첫 번째 요소를 반환합니다.

 

Array.prototype.findIndex()

찾아진 아이템의 index 번호를 반환

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

const b = fruits.findIndex(fruit => {
  return /^B/.test(fruit)
})
console.log(b) // 2
const b = fruits.findIndex(fruit => /^B/.test(fruit))
console.log(b)

 

Array.prototype.includes()

배열 데이터에 인수로 사용된 특정한 데이터가 포함되어 있는지를 확인해주는 메소드

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

const a = numbers.includes(3)
console.log(a) // true

const b = fruits.includes('heropy')
console.log(b) // true

 

Array.prototype.push()

원본이 수정됨

맨 뒤에 특정한 데이터를 추가

Array.prototype.unshift()

원본이 수정됨

맨 앞에 특정한 데이터를 추가

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

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

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

 

Array.prototype.reverse()

배열이 뒤집어짐

원본이 수정됨

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)// ['Cherry', 'Banana', 'Apple']

 

Array.prototype.splice()

원본이 수정됨

splice(index, 아이템을 몇 개 지울지)

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

numbers.splice(2, 1)
console.log(numbers) // [1, 2, 4]

numbers.splice(2, 2)
console.log(numbers) // [1, 2]

 

splice(index, 아이템을 몇 개 지울지, 추가할 것)

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

numbers.splice(2, 0, 999)
console.log(numbers) // [1, 2, 999, 3, 4]


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

numbers.splice(2, 1, 999)
console.log(numbers) // [1, 2, 999, 4]

fruits.splice(2, 0, 'Orange')
console.log(fruits) // ['Apple', 'Banana', 'Orange', 'Cherry']

 

반응형

'Online Class > DevCamp' 카테고리의 다른 글

React | 리액트 기본  (5) 2024.07.16
정규표현식  (1) 2024.07.14
JS 클래스 | 생성자 함수(prototype), this, ES6 classes, 상속(확장)  (0) 2024.06.12
Git | 마크다운(Markdown)  (0) 2024.06.12
Git | 명령 정리  (0) 2024.06.12