JS Objects
- Property = KEY + VALUE
Ex) username: ---> 'crazyCatLady'
upvotes: ---> 7
text ---> 'great post!'
LOOPS
1)
for(let i = 1; i<=10; i++){
console.log(i)
}
2)
let str = 'Da ba dee da ba daa'
let result = ''
for (let i = 0; i<=5; i++) {
result += str;
console.log(result);
}
for(let i = 0; i<=20; i+=2) {
console.log(i); //짝수 출력.
}
for(let i = 100; i>=0; i-=10) {
console.log(i); //10씩 작아지는.
}
const animals = ['lions', 'tigers', 'bears']
for(let i = 0; i < animals.length; i++) {
console.log(i, animals[i]);
}
//0 'lions'
//1 'tigers'
//2 'bears'
for(let i = animals.length-1; i; i--) {
console.log(animals[i]);
}
const people = ["Scooby", "Velma", "Daphne", "Shaggy", "Fred"];
for(let i = 0; i < people.length; i++) {
console.log(people[i].toUpperCase());
}
for (let i = 0; i < 10; i++) {
console.loog(`i is ${i}`)
for (let j = 1; j < 4; j++ )
console.loig(`j is ${j}`)
}
const seatingChart= [
['kristen', 'Erik', 'Namita'],
['Geoffrey', 'Juanita', 'Antonio', 'Kevin'],
['Yuma', 'Sakura', 'Jack', 'Erika']
]
for(let i = 0; i<seatingChart.length; i++) {
const row = seatingChart[i];
console.log(`ROW # ${i + 1}`);
for(let j = 0; j<row.length; j++) {
console.log(row[j]);
}
}
While loops continue running as long as the test condition is true.
let count = 0;
while(count <10) {
count ++;
console.log(count);
}
const SECRET = 'BabyHippo'
let guess = prompt("Enter the secret")
while(SECRET !== guess) {
guess = prompt("Enter the secret ");
}
console.log("Congratulations !")
let input = prompt("Enter Something!");
while(true) {
input = prompt(input);
if (input === "stop coping me"){
break;
}
}
// 정답 범위 정하기.
let maximum = parseInt(prompt("Enter the maximum number !"));
while(!maximum) {
maximum = parseInt(prompt("Enter a valid number !"));
}
//맞춰야할 숫자
const targetNum = Math.floor(Math.random() * maximum) + 1
console.log(targetNum);
let guess = parseInt(prompt("Enter your first guess "));
let attempts = 1 //시도횟수 산출.
while(parseInt(guess !== targetNum)) {
attempts ++;
if (guess === 'quit') //그만둔다하면 while 문 종료
break;
if(guess > targetNum) {
guess = (prompt("Too high! Enter a new guess"));
}
else if (guess < targetNum ) {
guess = (prompt("Too low! Enter a new guess"));
}
}
if (guess === 'quit'){
console.log("OK, YOU QUIT ! ")
} else {
console.log("CONGRATS YOU WIN !")
console.log(`You got it ! It took you ${attempts} guesses `);
}
For...Of
for (variable of iterable) {
statement
}
const subreddits = ['cringe', 'books', 'chicken', 'funny', 'pics', 'soccer'];
for (let sub of subreddits) {
console.log(`visit reddit.com/r ${sub}`);
}
for (let row of seatingChart) {
for(student of row) {
console.log(student);
}
}
String 자체도 for문을 돌면서 출력 가능.
for (let char of "hello world") {
console.log(char);
}
For ... in
const testScores = {
keenan : 80,
damon: 67,
kim:89,
shawn : 44,
marlon: 33,
elvira: 37
}
for (let person in testScores) { //'in'은 key를 지정해줌.
console.log(person);
}
const testScores = {
keenan : 80,
damon: 67,
kim:89,
shawn : 44,
marlon: 33,
elvira: 37
}
key 값들만 추출 : Object.keys(testScores)
value 값들만 추출: Object.values(testScores)
키-값 쌍으로된 중첩된 배열 추출: Object.entries(testScores)
//점수의 총합
let sum = 0 ;
for (let score of Object.values(testScores)){
sum += score;
console.log(sum);
}
//점수 평균
let sum = 0;
let scores = Object.values(testScores)
for (let score of scores ){
sum += score;
console.log(sum / scores.length);
}
<html code>
<!DOCTYPE html>
<html lang="en">
<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>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - List All Todos</li>
<li>"delte" - Remove Specific Todo</li>
<li>"quit" - Quit App</li>
</ul>
<script src="app.js"></script>
</body>
</html>
<css code>
let input = prompt("what would you like to do? ");
let todos = [];
while (input !== 'quit' && input !== 'q') {
input = prompt('what would you like to do? ');
if (input === 'new') {
const todo = prompt('Enter the Todo ');
todos += todo;
console.log(`${todos} added to the list ! `);
} else if(input === 'list') {
console.log('****************');
for(let i = 0; i < todos.length; i++){
console.log(`${i}: ${todos[i]}`);
}
console.log('****************');
} else if(input === 'delete') {
const index = paseInt(prompt('Ok, enter an index to delete !'));
if(!(Number.isNaN(index))) {
const deleted = todos.splice(index, 1);
console.log(`Ok, deleted ${deleted[0]}`);
}
else{
console.log("Unknow index")
}
}
}
console.log('OK QUIT THE APP ');
DEFINE
funciton funcName() {
//do something
}
RUN
funcName(); //run once
funcName(); //run again !
ARGUMENTS
Ex) function greet(person) {
console.log(`Hi, ${person}!`);
}
greet('Evlis');
1)
function greet(firstName, lastName) {
console.log(`Hey there, ${firstName} ${lastName[0]}.`
}
2)
function repeat(str, numTimes) {
let result = '';
for (let i = 0; i < numTimes; i++ {
result += str;
}
console.log(result);
}
RETURN
function add(x,y) {
if (typeof x !== 'number' || typeof y !== 'number') {
return false;
}
}
Last Element Exercise
function lastElement(numArray) {
if (numArray == '') {
return null;
} else {
return numArray[numArray.length -1];
}
}
let bird = 'Scarlet Macaw';
function birdWatch() {
//let bird = 'Great Blue Heron';
console.log(bird);
}
birdWatch();
-> Scarlet MacaW 출력
Block
LEXICAL SCOPE
function outer() {
let hero = 'Black Panther';
function inner() {
let cryForHelp = `${hero}, please save me!`
console.log(cryForHelp);
}
inner();
}
const square = function (num) {
return num * num;
}
square(7);
HIGHER ORDER FUNCTIONS
function callTwice(func) {
func();
func();
}
function laugh() {
console.log("HAHAHA");
}
callTwice(laugh)
function makeBetweenFunc(min, max) {
return func(num) {
return num>=min && num<=max;
}
}
const isChild = makeBetweenFunc(0,18)
isChild(20) : Flase !
METHODS
const myMath = {
PI: 3.141592,
square: function (num) {
return num * num;
},
cube: function (num){
return num **3;
}
}
SHORTHAND (function 쓰지않아도됨)
const myMath = {
PI: 3.141592,
square (num) {
return num * num;
},
cube (num){
return num **3;
}
}
Methods Exercise
const square = {
area (side) {
return side * side;
},
perimeter(side) {
return 4 * side;
}
Use the keyword "this" to access other properties on the same object.
The value of 'this' depends on the invoation context of the function it is used in.
const meow2 = cat.meow;
console.log("THIS IS" , this);
Egg Laying Exercise
const hen = {
name: 'Helen',
eggCount: 0,
layAnEgg() {
this.eggCount += 1;
return "EGG";
}
}
오류를 발생시키려 하거나 오류가 날 것으로 예상될 때 사용.
try {
hello.toUpperCase();
} catch {
console.log("ERROR!");
}
function yell(msg) {
try {
console.log(msg.toUpperCase().repeat(3))
} catch (e) { // e : "error"
console.log(e)
console.log("Please pass a string nest time !")
}
}