개인적 정리) wecode 1주차 javascript

개발자 우니·2020년 6월 24일
0

parameter 의 유무확인 :
'sth' == undefined (따옴표 없음)
type of 'sth' !== 'undefined' (따옴표있음)

function checkDate (year, month, day) {
	if (typeof day !== 'undefined') {
    	return (year + '/' + month + '/' + day);
    } else if (typeof month !== 'undefined'){
    	return (year + "년 " + month + "월");
    } else if (typeof year !== 'undefined){
    	return (year + "년");
    }

}

checkDate(2020); --- 2020년
checkDate(2020, 12); --- 2020년 12월
checkDate(1999, 8, 12); --- 1999/8/12 

undefined, null 의 차이

  • undefined : 말 그대로 변수는 있으나 어떤 값이 정의되지 않은 상태
    위의 checkDate(2020); 를 예로 들면 현재 month, day는 지정이 되지 않았으므로 undefined 상태가 된다. (2020/undefined/undefined)
    var number;
    number는 특정값을 할당받지 않았으므로 undefined 상태이다.
  • null : null값을 할당받은 상태(빈값을 할당)로 undefined와 다르게 객체로 취급
var a = null;
var b;
console.log(a == b)  ---- true (== 는 자료형이 다르면 자동 형변환으로 인해 true로 나타남)
console.log(a ===b) ---- false (자료형 타입이 다르므로 엄격하게는 다르다)
console.log(typeof a) ---- object (null 객체 취급)
console.log(typeof b) ---- undefined


array [] 가 empty 가 아닌지 알아볼 조건

typeof Array != "undefined" 
Array != null 
Array.length != null
Array.length > 0

array 안에 숫자 중 최댓값, 최솟값 찾기 :
Math.min() / Math.max() / Math.max.apply()

console.log(Math.max(1, 2, 3)); --- 3 산출
console.log(Math.min(7, 8, 9)); --- 7 산출

array 의 경우 배열의 길이가 길수록 효율성이 떨어지므로 .apply() 붙여서 두번째 인자의 값을 array로 받아서 안의 요소를 인자로 전부 넘겨줍니다.

let arr = [0, 1, 2, 3, 4, 5, 6, 7];
Math.max(null, arr); ---- arr 안의 요소를 검색 7 산출
Math.max([0, 1, 2, 3, 4, 5, 6, 7]); --- NaN

boolean : true / false

true로 변환되는 값
문자열: 비어 있지 않은 모든 문자열
숫자: 0이 아닌 모든 숫자
객체: 모든 객체 ({}, [] 모두 포함)

false로 변환되는 값
문자열: "" (빈문자열)
숫자: 0, NaN
객체: null
undefined

let number = 0;
let msg = "hello";

if (number) {    ---- 실행안됨 false
}
if (msg) {      ---- 실행됨 true
}

숫자의 시작을 0으로 할때는 string으로

let phone = 012345;
console.log(phone);     ---- undefined
console.log(phone.length);  ----- undefined

let phone = "012345";
console.log(phone);     ---- 012345
console.log(phone.length);  ----- 6

위와 같이 str 타입으로 해줘야 인식한다

원하는 글자가 있는지 찾아내기 :
sth.indexOf("원하는 글자"); : 순서 숫자로 나타남
sth.charAt("숫자"); : 숫자의 순서에 있는 글자 추출
sth.substring(2,4); : 순서 2부터 4까지 글자 추출
sth.substr(2,4); : 위와 비슷하지만 두번째 숫자 4는 추출할 length를 의미한다. (=2에서부터 4개의 글자를 추출하겠다!)

.string(1,2); 과 .substring(1,2); 는 글자를 설정 부분까지 추출한다는 점에서 거의 같으나 .substring(2,1);은 첫번째 설정 숫자를 두번째 숫자보다 더 큰 숫자를 넣을 수 있다는 차이가 있다.

sth.indexOf(); -- 원하는 글자가 있는 경우 글자가 위치한 순서가 숫자로 뜨게 되고, 없는 경우는 -1 이라는 값이 뜨게 된다. 그래서 조건문에서 이를 활용하면 if (sth.indexOf("글자") !== -1) 는 "글자"가 있다는 조건이라면 의 의미가 된다.

확장해서 원하는 글자를 찾아내고 그 위치를 기준으로 글자를 잘라서 추출할 수 있다 : slice( , )

let example = "I want an apple and banana.";
let mark = example.indexOf("apple");
console.log(mark); ---- 10 이 산출

let select = example.slice(mark, mark+6);
console.log(select); ---- apple 만 뽑아낸다

number 과 string 의 형변환 :
number -> string : number.toString(); / number + " " ; 로 새로 변수 지정
string -> number : parseInt("str"); 정수형으로 / parseFloat("str"); 실수형으로 / Number("str");

parseInt("999.9");  ----- 999
parseFloat("999.9"); ---- 999.9

20.toString();  ---- "20"의 str 타입으로
20 + ""; --- 동일

min ~ max 사이의 랜덤 정수값 구하기

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

Math.ceil() ---- 같거나 올림해서 정수값

min ~ max 사이의 값을 랜덤으로 구하기위해 min을 먼저 빼주면 0 ~ (max-min) 사이의 범위가 된다. 둘 다 정수값이므로 (max-min)은 최소 0부터 최대 미지의 정수값이 된다. Math.random() 은 0~1 사이의 값이기 때문에 곱한다해도 최소 0~ (max-min) 값이 나오고 최종적으로는 처음에 빼준 min 을 다시 더해줌으로써 초기 조건을 만족할 수 있다.


객체(object) 와 프로퍼티 (property)
: object { property1: property value1, property2: property value2 ...}
객체 내의 프로퍼티 부를 경우는 object.property 구조로 호출한다. []대괄호를 쓸 경우엔 아래와 같이 한다.

let student = {
	name: mary
    };
console.log(student.name);    ---- mary 산출

[] 대괄호를 사용할 경우는 property 를 변수로 설정하고
let set = "name";
console.log(student[set]);    --- mary 산출
또는 property string 으로 입력
console.log(student["name"]); --- mary 산출
console.log(student[name]);   ---- undefined

property 에 property 추가할때 .새로운property(value)

let myObj = {
  property1: "hello",
  property2: [1,2,3,4,5],
  property3: {
    childproperty: "haha"
  }
};
console.log(myObj.property3.sibling([1,2]));
하면 property3에 sibling : [1,2] 가 추가된다.

 property3: {
    childproperty: "haha",
    sibling : [1,2]
  }

비슷한 모양의 객체를 계속 만들어야 한다면 :
class 사용 & constructor 함수

class Car{
	constuctor (name, color){
    	this.name = name;
        this.color = color;
    }
}

const bmw = new Car('bmw', 'white');
console.log(bmw); 하면
--- class Car {
	name: bmw,
    color: white
} 출력

class '이름' 은 항상 대문자로 시작하고 camelcase로 적는다. Car class의 인스턴스를 생성할 때마다 constructor 메서드가 호출된다. class의 범위내에서 지정할 때 this 를 사용한다.
const '변수명' = new Car( , ) : new 를 써줘야 클래스를 불러온다.

class MyMath {
  constructor (num1, num2){
   this.num1 = num1;
   this.num2 = num2;
  }
  add(){
    this.sum = this.num1 + this.num2;
  }
  substract(){
    this.sub = this.num1 - this.num2;
  }
  multiply(){
    this.mul = this.num1 * this.num2;
  }
  getNumber (){
    this.list = [this.num1, this.num2];
  }
}
const hey = new MyMath(3,5); 
console.log(hey); 만 할 경우에는 3과 5만 들어가있다.

hey.add();
hey.substract();
console.log(hey); ---add와 substract까지만 했고 콘솔할 경우 (거기까지만 추가된다!)

나머지 multiply, getNumber 까지하고 콘솔하면 아래와 같은 결과가 나온다.

this.sth ---- sth 이란 property key가 생기면서 function 값이 property value로 할당된다.


ES6 ] .forEach(값, 인덱스)

let arr = ['a', 'ab', 'c', 'asd'];

arr.forEach((what, index) => {
	if (what === 'c'){
    return index;
	}
})
------ 2 산출 ('c'의 index )

Object.keys(); : {} 객체가 가지고 있는 키들의 목록을 배열해주는 메소드
[] 리스트는 for 문을 돌리거나 .map() , .forEach() 사용
Object.values(); : 객체의 키가 가진 값들을 배열
Object.entries(); : 객체의 키와 값을 나란히 []로 배열

const fruit = {
  name: 'melon',
  weight: 4350,
  price: 16500,
  isFresh: true
}

Object.keys(fruit) ;
// 결과 ['name', 'weight', 'price', 'isFresh']

const values = Object.values(fruit);
// 결과 values === ['melon', 4350, 16500, true]

const entries = Object.entries(fruit)
//결과
entries === [
  ['name', 'melon'],
  ['weight', 4350],
  ['price', 16500],
  ['isFresh', true]
]

for(let i=0; i<array.length; i++)
= 다르게 표현하면
for (let i in array)

profile
It’s now or never

0개의 댓글