자료형 = 타입
arr1=[1,2,3,4]
arr2=arr1 //새로운 배열 셍상
arr2=[1,2,3,4]
arr2[3]=0 //0
arr2 =[1,2,3,0] >> 참조된 값을 바꿈(arr값까지 변함)
new Array(1,2,3,4) 인 것
자료형의 값 복사
자바스크립트는 기본 자료형의 값을 복사할 때 값을 완전히 복사한다.
=을 이용하여 값 복사
var a=100;
var b= a;
a=200;
alert(a); //200
alert(b); //100
? array[ ] /object/ 함수
객체에 변수를 저장
실제 값을 저장하는 것이 아니라 객체를 메모리 어딘가에 만들고, 객체의 참조(위치 값)를 저장하게 된다.
인자를 통해 변수를 제어할 수 있다.
"파선아실"
파라미터
함수 선언 시 초기 값
인자
함수 호출 시 전달된 값
반복 가능한(iterable)객체는 배열을 일반화한 객체. 이터러블이라는 개념을 사용하면 어떤 객체에든 for ..of반복문을 적용할 수 있다.
배열은 대표적인 이터러블. 배열 외에도 다수의 내장 객체가 반복 가능
object는 반복x => map 나옴!
객체 :객체 또는 object는 클래스에서 정의한 것을 토대로 메모리에 할당된 것으로 데이터 또는 식별자에 의해 참조되는 공간.
클래스 객체는 자료와 그 자료를 다루는 명령의 조합을 포함하여 객체가 메시지를 받고 자료를 처리하며 메시지를 다른 객체로 보낼 수 있도록 한다.
프로토타입 기반 객체지향> js
js > 클래스 개념 (2015) 새로생김 [ES6]
new 결과물 = 인스턴스
js에서는 new = 타입생성자 라고 함.
다른 언어 class라고 부름.
할당 연산자(=) 를 이용하면 할당
키워드없이 변수 선언하면 자동으로 var 로 생성
js에 있는 모든 것들은 객체이다.
'hello' => 인스턴스, 객체 ,원시값, 리터럴
'hello'[0] ='h'
'hello'.length =5
객체라서 내장함수 .찍어서 값이 나온다.
this.함수명(); 으로 생각하면 됨
만약
window 전역객체 - 최상 존재하는 전역 객체.
함수 -전역객체 안에 있는것.
this는 자기를 호출한 객체를 찾는다. 그래서 윈도우를 가리키고 있는것.
hello 객체 안에 뭐가 들어있는지
console.log(this) 했을때 myObj가 아닌지 의문!?
콘솔에 출력된 {val1: 100, func1: f} 자체가 myObj 자체이다!
func1()의 this는 myObj이다.
0이상 1미만의 랜덤 변수! 1은 절대로 나오지 않는다!
Math.random()10;
올림이나 반올림은 확률에 차이가 생긴다. -> floor로 버리면 깔끔하게 정리 가능.
Math.floor(Math.random()10);
10을 곱했더니 10 미만의 수가 나온다.
만약 5보다 작은 수 원하면 Math.floor(Math.random()*5); 이용할 것 //0~4
+2 를 하면 범위는 2~6 나올 것.
랜덤한 숫자를 만드는 함수로.!
구하고 싶은 숫자의 범위 지정.
원하는 범위 숫자를 마음대로 뽑을 수 있다.
어떤 숫자 이상의 수를 뽑고 싶다.
false : 0, '', null, undefined, NaN
논리연산자 순서 NOT > AND > OR
function randomNum(min, max){
return Math.floor(Math.random()*(max-min)+min);
}
function tryLotto(...input) {
if (input.length !== 6) {
console.log('숫자를 6개 입력해야 합니다.');
return;
} else if (input.length !== new Set(input).size) {
console.log('숫자를 중복되지 않게 입력해야 합니다.');
return;
} else if (input.some(v => !Number.isInteger(v) || v > 45 || v < 1)) {
console.log('1부터 45까지 숫자 중 하나를 입력해야 합니다.');
return;
}
const selected = [];
let count = 0;
while (count < 7) {
const selectedNum = randomNum(1, 46);
if (!selected.includes(selectedNum)) {
count++;
selected.push(selectedNum);
}
}
console.log(`당첨번호: ${selected.slice(0, 6).join(' ')} | 보너스: ${selected[6]}`);
const nums = input.filter(v => selected.slice(0, 6).includes(v));
switch (nums.length) {
case 0: case 1: case 2:
console.log('꽝!');
break;
case 3:
console.log('★ 5등 당첨! ★');
break;
case 4:
console.log('★★ 4등 당첨! ★★');
break;
case 5:
if (input.includes(selected[6])) {
console.log('★★★★ 2등 당첨!! ★★★★');
nums.push(`보너스 ${selected[6]}`);
} else console.log('★★★ 3등 당첨!! ★★★');
break;
case 6:
console.log('★★★★★ 1등 당첨!!! ★★★★★');
}
if (nums.length > 0) console.log(`내가 맞춘 번호: ${nums.join(' ')}`);
> }
// 랜덤 숫자 뽑는함수
function randomFunc(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
// 뽑은 번호 담을 배열 준비
let lottoArr = [];
// 6개 뽑아서 lottoArr에 담는함수
function lottoGenerator() {
// 배열이 꽉차기 전까지 반복 (6개 까지)
while (lottoArr.length < 6) {
let result = randomFunc(1, 46);
// 중복 판단하기위해 필요한 변수
let isGot = false;
// 중복 판단
// lottoArr 의 요소를 순회
lottoArr.forEach((element) => {
// 요소가 result 와 같다면 중복!
if (element === result) {
// 중복됐다고 표시!
isGot = true;
}
});
// 중복이 안되었다면 배열에 뽑은숫자 추가 (중복이 되었다면 if문에 못들어가서 추가하지않음)
if (!isGot) {
lottoArr.push(result);
}
}
// 여기에 도달했을땐 배열이 꽉~채워짐
return lottoArr;
}
console.log(lottoGenerator());
function randomFunc(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function lottoGenerator() {
let lottoArr = [];
while (lottoArr.length < 6) {
let result = randomFunc(1, 46);
// 중복 판단, 다만 include는 IE지원안됨
// 중복되는 숫자가 없다면
if(!lottoArr.includes(result)) {
lottoArr.push(result);
}
}
return lottoArr;
}
console.log(lottoGenerator());
Size방법
// let lottoArr = [];
let lottoSet = new Set();
function lottoGenerator() {
while (lottoSet.size < 6) {
let result = randomNum(1, 46);
// let isGot = false;
lottoSet.add(result);
// 중복 판단
// lottoArr.forEach(element => {
// if (element === result) {
// isGot = true;
// }
// });
// 중복이 없다면 배열에 추가
// if (!isGot) {
// lottoArr.push(result);
// }
// if (!lottoArr.includes(result)) {
// lottoArr.push(result);
// }
}
return lottoSet;}
array: length, push
set: size, add
HTML문서의 내용을 트리형태로 구조화하여 웹페이지와 프로그래밍 언어를 연결시켜주는 역할
이때 각각의 요소와 속성, 콘텐츠 표현 단위를 노드(node)라 한다.
document 객체를 통해 HTML문서에 접근 가능. document는 브라우저가 불러온 웹페이지를 나타내며, DOM트리의 진입점 역할 수행.
//해당하는 Id를 가진 요소에 접근하기
document.getElementById();
//해당하는 모든 요소에 접근하기
document.getElementsByTagName();
//해당하는 클래스를 가진 모든 요소에 접근하기
document.getElementsByClassName(); ex) 'li'
// 해당하는 클래스를 가진 모든 요소에 접근하기
document.getElementsByClassName();
// css 선택자로 단일 요소에 접근하기
document.querySelector(“selector”);
// css 선택자로 여러 요소에 접근하기
document.querySelectorAll(“selector”);
=> jQuery 사용
이 클래스를 가진 요소 선택
$(".myClass").css()
이벤트
js이벤트설명
토글이란 하나의 설정 값으로부터 다른 값으로 전환하는 것
리팩토링 > 중복되는 문장 간결하게.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="reset.css">
<style>
.canvas {
width: 500px;
height: 500px;
margin: 0 auto;
background-color: black;
}
.canvas.red {
background-color: red;
}
.canvas.yellow {
background-color: yellow;
}
.canvas.green {
background-color: green;
}
ul {
display: flex;
justify-content: space-around;
width: 500px;
margin: 50px auto 0;
}
</style>
</head>
<body>
<div class="canvas"></div>
<ul>
<li><button type="button" class="btn-red">빨강</button></li>
<li><button type="button" class="btn-yellow">노랑</button></li>
<li><button type="button" class="btn-green">초록</button></li>
</ul>
<script>
const canvas = document.querySelector('.canvas');
const btnRed = document.querySelector('.btn-red');
const btnYellow = document.querySelector('.btn-yellow');
const btnGreen = document.querySelector('.btn-green');
let btnArr = [btnRed,btnGreen,btnYellow];
btnArr.forEach((item)=>{
item.addEventListener('click', () => {
//방법2개 지우기
//canvas.classList = 'canvas';
item.classList.remove('red','yellow','green');
//조건문
if (item.className==='btn-red') {
canvas.classList.add('red');
}else if (item.className==='btn-yellow') {
canvas.classList.add('yellow');
}else { canvas.classList.add('green');
}
})})
</script>
</body>
</html>
오늘 github에 올릴 것
1. 로또번호 랜덤뽑기 사이트 - > github올리기
2.