알고리즘

Imnottired·2023년 3월 21일
0
post-thumbnail

Array.prototype.reverse()

reverse는 string이 아닌 Array에서 가능하다.
mutable 이다.

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

replace();

string이 타겟이며 바꿔줄 수 있다.
인상적이었던 것은 정규식을 이용해 문자만 거를 수 있다.

replace(/[^a-z]/g, "") 식으로 모든 문자만 남기고 제거할 수 있다.
정규식에서 ^는 부정을 의미한다.
주의할 점은 사용하기 전에 정규식이 소문자를 사용하기에 소문자로 통일해야한다

  • 일반적인 예시
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"


const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace

for of문 string 가능

let word = "string";
for (let i of word) {
  console.log(i);
}

for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.

라고 한다 기억할 것

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...of

isNaN()

숫자가 맞을 경우엔 false
아닐경우에는 true 이를 이용에 숫자만 걸러낼 수 있다.

let word = input[0];
let result = "";
for (let i of word) {
  if (!isNaN(i)) {
    result += i;
  }
}
console.log(parseInt(result));

parseInt

정수로 만들어줌


document.writeln(parseInt("10")); // 10
document.writeln(parseInt("-10")); // -10
document.writeln(parseInt("10.9")); // 10
document.writeln(parseInt(10)); // 10
document.writeln(parseInt("10n")); // 10
document.writeln(parseInt("10nnn13")); // 10
document.writeln(parseInt("    10")); // 10
document.writeln(parseInt("10      ")); // 10
document.writeln(parseInt("k10")); // NaN
document.writeln(parseInt("")); // NaN

https://hianna.tistory.com/386

parseInt 대체하는 법

아래를 통해 들어오는 값을 숫자로 변환하고 *10을 이용하여 대체할 수 있다.

let word = input[0];
let result = "";
for (let i of word) {
  if (!isNaN(i)) {
    result = result * 10 + Number(i);
  }
}
console.log(result);
profile
새로운 것을 배우는 것보다 정리하는 것이 중요하다.

0개의 댓글