m1ndy5's coding blog

JavaScript 기초 - 반복문, 객체, 함수, Array & String 등 본문

프론트엔드/java script

JavaScript 기초 - 반복문, 객체, 함수, Array & String 등

정민됴 2023. 4. 30. 15:38

반복문

// 0 ~ 9까지 새로로 찍힘
for(let i = 0; i < 10; i++){
    console.log(i);
}
const s = "javascript";

// key(index)값에 접근 for in
for(const i in s){
    console.log(i);
} // 0 ~ 9까지 새로로 찍힘

// value(요소)값에 접근 for of
for(const ele of s){
    console.log(ele);
} // j ~ t까지 새로로 찍힘

// array 요소를 순회 array.forEach(ele => {});
const color = ['red', 'orange', 'blue', 'green'];

color.forEach(ele => {
    console.log(ele);
}); // red ~ green까지 새로로 찍힘

color.forEach((ele, i) => {
    console.log(ele, i);
}); // red 0 ~ green 3까지 새로로 찍힘

// 문자열을 array로 만드는 방법
[...문자열]

객체

여러 타입의 데이터들을 하나로 묶어서 사용할 수 있는 타입
객체의 프로퍼티로 객체가 올 수도 있고, 배열 또는 함수가 올 수도 있음

const ob1 = { a: 'abc', b: 25, c: {}};
// 프로퍼티에 접근할 때는 객체.프로퍼티
console.log(ob1.a); // abc

const a = 'abc';
const b = 25;
const c = {};
const ob2 = { a: a, b: b, c: c};
console.log(ob2.b); //25

// 단축 속성명
const ob3 = {a, b, c};
console.log(ob3.c); // {}
// 객체 리터럴 방식을 활용한 객체 생성
const ob1 = {
    userName: 'mindyo',
    age: 25,

    printName: function(){
        console.log(this.userName);
    }
};
ob1.printName(); // mindyo

// new Object() 잘 안씀
const ob2 = new Object();

// property 객체 초기화
function User(userName, age){
    this.userName = userName;
    this.age = age;
}

// 이렇게도 사용 가능
function User(userName, age){
    return {userName, age};
}

const user = new User('mindyo', 25);

Function

함수는 값처럼 쓰일 수 있음 -> 변수에 저장가능

const mul = function(a, b){
    return a*b;
};

console.log(mul(1, 2));

const hello = userName => `hello ${userName}`;

console.log(hello('mindyo'));

Arrow Function

// 두 수 a, b를 받아서 합을 반환하는 함수, 함수 구현부가 2줄 이상이면 {} 필수!
const sum = (a, b) => a + b; // 암묵적인 return

// 코드가 한줄인데 객체를 반환하고 싶다?? -> 소괄호 추가
const a = 'm';
const b = 2;

const person = (a, b) => ({a, b});

console.log(person(a, b)); // {a: 'm', b: 2}

// 파라미터 1개 또는 0개
const square = x = > x*x;
const greet = () => 'hello';

Callback Function

함수를 매개변수로 주고 함수 안에서 함수를 실행

// 람다 함수로도 표현 가능
function greeting(userName){
    console.log(`Hello ${userName}`);
}

function userInput(name, callbackFn){
    callbackFn(name);
}

userInput('mindyo', greeting); // Hello mindyo

Array

const color = ['red, 'orange', 'green'];

console.log(typeof color); // 기본 타입을 제외한 모든 것은 객체

// 정말 Array 타입인지
console.log(Array.isArray(color));

// array 크기 체크
console.log(color.length);

// 크기를 벗어나면 undefined라고 뜸
console.log(color[4]) // undefined

// 요소의 삭제, 희소배열이 생성되어 비추천(빈 곳이 empty로 뜸)
delete color[1];
console.log(color); // ['red', empty, 'green']

// 요소 추가
color.push('blue');

// Array.splice(삭제 시작할 인덱스, 삭제할 요소 개수)
color.splice(1, 1); // 인덱스 1번 값 1개 삭제

String

// 문자열 리터럴로 생성
const s = 'hello javascript';
// 생성자를 통해 생성 -> 잘 안씀
const st = new String('hello javascript');

// string[] vs string.charAt() -> 크기를 벗어났을 때 차이가 있음
const str = "hello";
console.log(str[7]); // undefined
console.log(str.charAt(7)); // "" -> 빈 문자열