728x90

배열(array)의 값(element)을 하나씩 받아서 내가 작성한 function을 실행해주는 helper method

💻Example Code

const arr = [ 1, 2, 3 ];

const received = arr.forEach( num => console.log(num) );

console.log( arr );
console.log( received );

실행 결과

forEach는 제공 받은 function Array의 각 element마다 실행해주기만 한다.
function의 결과를 return 해주지 않는다. forEach의 return 값은 undefined다.

따라서 위의 결과처럼, arr를 한 번씩 실행해주고 있는 것을 볼 수 있으며, 기존 arr값이 변하지 않는 것을 볼 수 있다.
또한, return값이 있는지 확인하기 위해 선언했던 received를 출력하면 undefined가 출력되는 것을 볼 수 있다.

🎃실전 예제

forEach를 사용하여 ul에 li element를 추가해주는 예제
위의 예제가 실행된 HTML 페이지

위의 간단한 예제처럼 사용할 수 있다. objArr는 직접 작성해줬지만, 어딘가에서 받아올 data라 생각하면 된다.

😋 개발을 진행할 때, 많은 양의 데이터를 받아와서 하나씩 실행해줄 때 매우 유용하다.
매우 자주 쓰이는 helper method이므로 필수적으로 알고 있어야 한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

 

Array.prototype.forEach()

The forEach() method executes a provided function once for each array element.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.abs()  (0) 2020.01.28
Math.PI  (0) 2020.01.28
Math.pow()  (0) 2020.01.22
Math.random()  (0) 2020.01.18
Math.ceil()  (0) 2020.01.18
728x90

✨ 무작위(random)숫자를 얻기 위한 helper method

💻Example Code

const randomNum = Math.random();
const max = 3;

console.log( randomNum ); // 0 ~ 0.99999...
console.log( randomNum * max ); // 0 ~ 2.9999.....

위 코드를 3번 실행한 결과

기본적으로, Math.random()은 0 ~ 0.999...까지 값을 얻을 수 있다(1은 포함되지 않는다)
하지만, 위 코드처럼 max값을 곱해주면 0 ~ 2.999...까지 값을 얻을 수 있다(3은 포함되지 않는다)
이렇게 범위를 정해서 내가 원하는 random 값을 받아볼 수 있다.

📌 만약 1부터 3까지 값을 받고 싶다면?

Math.ceil( Math.random * 최대 범위 )
위와 같이 ceil(올림) method를 사용해주면 된다(여러가지 다른 방법도 있다)

console.log( Math.ceil(Math.random() * 3) );

위 코드를 3번 실행한 결과

📌 function을 사용하여 간편하게 이용하는 방법도 있다.

function getRandomInt(max){
return Math.floor( Math.random() * max ) + 1; }

const max = 3;

console.log( getRandomInt(max) );

위 코드를 3번 실행한 결과

위 function에서는 Math.floor( Math.random() * max ) + 1; 로 작성했다.
즉, 0 ~ 2.999...범위의 random 숫자를 버림(floor)해주고 +1을 더해 주는 방식이다.
이렇게 작성해도 1~3까지 범위의 random 숫자를 받아볼 수 있다.

😋 기본적으로 구구단 게임이라든지, 무언가 변칙적인 개발이 필요할 때 자주 사용되는 method!
종종 쓰이기 때문에, 한 번 잘 이해해두고 앞으로 쉽게 사용하자.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

 

Math.random()

The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.forEach()  (0) 2020.01.23
Math.pow()  (0) 2020.01.22
Math.ceil()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.map()  (0) 2020.01.11
728x90

✨ '1.23'과 같이 소수점과 함께 있는 수를 올림 해주는 helper method

💻Example Code

const floatNum = 1.23;
const minFloatNum = -7.5;

console.log( Math.ceil(floatNum) );
console.log( Math.ceil(minFloatNum) );

실행 결과

😋 소수점 올림을하여 정수(Integer)가 필요할 때, 편리하게 사용할 수 있다. 자주 쓰이는 method.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

 

Math.ceil()

The Math.ceil() function always rounds a number up to the next largest whole number or integer.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.pow()  (0) 2020.01.22
Math.random()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
728x90

✨ 내가 제공한 function통과(pass)하는 값(element)들을 새로운 배열로 만들어주는 helper method

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const passedArr = originArr.filter( num => num !== 3 );

console.log(originArr);
console.log(passedArr);

실행 결과(3이 없어진 배열이 새로 생긴 것을 볼 수 있다)

ex2)
const originArr = [ 'a', 'b', 'c', 'd', 'e' ];
const passedArr = originArr.filter( char => char !== 'a' );

console.log(originArr);
console.log(passedArr);

실행 결과('a'가 제거된 것을 볼 수 있다)

😋 배열에서 내가 원하지 않는 값을 제거하고(솎아내고) 새로운 배열을 생성한다.
map()과 마찬가지로 정말 정말 많이 쓰인다. 꼭 알아둬야할 helper다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.random()  (0) 2020.01.18
Math.ceil()  (0) 2020.01.18
Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
728x90

기존 배열(array)에 어떠한 function(연산)을 적용한 후 새로운 array를 만들고 싶을 때 사용하는 helper method
(for loop같은 반복문을 이용하고 싶지 않을 때)

💻Example Code

ex1)
const originArr = [ 1, 2, 3, 4, 5 ];
const populatedArr = originArr.map( num => num * 2 );

console.log(originArr);
console.log(populatedArr);

실행 결과(기존 array는 그대로 있다)

ex2)

const originArr = [ '1', '2', '3', '4', '5' ];
const populatedArr = originArr.map( charNum => Number(charNum) );

console.log(originArr);
console.log(populatedArr);

실행 결과(String이 Number로 변경된 것을 볼 수 있다)

😋 map()의 괄호 안에 내가 원하는 function을 넣고, 기존 array에 있는 모든 값(element)를 불러와 실행시킨다.
굉장히 자주 쓰이는 helper method로써 꼭 알아둬야할 helper다. ex2)와 같이 String -> Number로 변경시키고 싶을 때도 자주 사용한다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Math.ceil()  (0) 2020.01.18
Array.prototype.filter()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
728x90

✨Array의 끝에 1개 또는 여러 개의 값을 넣어주는 helper method

💻Example Code

const arr = [ 'a', 'b', 'c' ];

arr.push('d');
console.log( arr );
arr.push('e', 'f');
console.log( arr );

실행 결과('d'와 'e', 'f'가 추가된 것을 볼 수 있다)

😋 스택(Stack) 자료구조(Data Structure)의 push()에서 사용할 수 있으며, 그 외에도 정말 정말 정말 많은 곳에서 쓰인다.
(스택 자료구조는 JavaScript - Data Structures에서 확인 가능하다)

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

 

Array.prototype.push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.filter()  (0) 2020.01.11
Array.prototype.map()  (0) 2020.01.11
Array.prototype.pop()  (0) 2020.01.04
Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
728x90

✨ array의 마지막 값을 제거하고, 제거된 값을 반환한다.
(기존 array가 제거된 상태로 갱신된다)

💻Example Code

const arr = [ 'apple', 'juice', 'flower' ];

console.log( arr.pop() );
console.log( arr );

실행 결과(마지막 값인 flower 반환, 새로운 array 갱신)

😋 큐(Queue) 자료구조(Data Structure)의 remove()에서 사용할 수 있으며, 그 외에도 pop()은 정말 많은 곳에 쓰인다.
array에서 아예 제거된다는 것을 명심하자.
(큐 자료구조는 JavaScript - Data Structures에서 확인 가능하다)

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

 

Array.prototype.pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.map()  (0) 2020.01.11
Array.prototype.push()  (0) 2020.01.06
Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
728x90

✨ 배열(array)의 가장 앞에 값을 넣어주고, 새로운 array의 길이를 반환하는 helper method
(Queue와 같이 First In이 필요한 상황에서 사용할 수 있다)

💻Example Code

const arr = [ 3, 4 ];
arr.unshift(1, 2);

console.log( arr );

실행 결과(기존 3, 4 앞에 1, 2가 삽입된 것을 볼 수 있다)

😋 큐(Queue) 자료구조(Data Structure)처럼 항상 값이 가장 앞에 들어가야하는 경우 사용할 수 있다.
큐 자료구조는 JavaScript - Data Structures에서 확인할 수 있다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

 

Array.prototype.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.push()  (0) 2020.01.06
Array.prototype.pop()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
728x90

✨ 주어진 array에서 찾고자하는 element의 index를 반환, 없다면 -1을 반환하는 helper method
(index는 가장 먼저 발견된 element 기준으로 반환된다)

💻Example Code

const arr = 'gamgongsa';

console.log( arr.indexOf('a') );
console.log( arr.indexOf('g') );
console.log( arr.indexOf('z') );

실행 결과('a'의 index는 1, 'g'의 index는 0, 'z'는 없기 때문에 -1)

😋 긴 문자열이 주어지고, 여기서 내가 원하는 알파벳이 있는지 없는지를 확인하고자 할 때 쓰기 좋은 helper method
알파벳 찾기(Find alphabet) 알고리즘 문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

 

Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.unshift()  (0) 2020.01.04
String.fromCharCode()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
728x90

✨ 내가 찾고자하는 Pattern(character or string etc)을 찾기에 유용한 helper method
(Pattern은 사실 Regular Expression(정규표현식)이지만 쉽게 표현하기 위해 사용하였다)

💻Example Code

const str = 'Hi There!!';
const matches = str.match(/[aeiou]/gi);

console.log( matches );
console.log( matches ? matches.length : 0 )

실행 결과(match된 내용과 배열의 길이)

😋 특히, 특정 문자열을 검색하는 알고리즘 문제를 풀거나, 개발을 할때 매우 유용하다. (단, RegExp를 잘 안다는 전제하에)
Vowels Algorithm(모음 찾기) 문제를 풀 때 잘 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29

+ Recent posts