TIL013_210402


TIL


🧸 感傷的



javascriptの関数を学びました.
📙 11時間
👍🏼 -
👎🏼 -

🚀 n/a.ターゲット

  • UdemyでJavascriptレッスン(264/682)
  • に参加
  • 毎日提出30日連続達成(13/30,4.02完了)
  • 23.24発見遷移(完了)
  • 明日学習カードを申請(後でUdemyを完了)
  • 完了
  • Jumpto Python(後で、JSに詳しい後)
  • [リンクリスト]
    Web Developer Bootcamp 2021
    現代javascriptチュートリアル

    📣 The Web Developer Bootcamp 2021: 19.195-21.216


    Loop


    nested loop


    for (let i = 1; i <= 10; i++) {
    console.log('i is: ${i})
    for (let j = 1; j < 4; j++) {
    console.log(' j is: ${j}')
    }
    }
    i is: 1
    j is: 1
    j is: 2
    j is: 3
    i is: 2 ....

    Whle loop


    let num = 0;
    while (num<10) {
    console.log(num);
    num++;
    }

    Break keyword



    Guessing game

    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) {
    	if (guess === 'q') break;
    	attempts++;
    	if (guess > targetNum) {
        	guess = prompt("Too high! Enter a new guess:");
        } else {
        	guess = prompt("Too low! Enter a new guess:");
        }
    }
    if (guess === 'q') {
    	console.log("OK, You quit");
    } else {    
    	console.log("CONGRATS YOU WIN!")
    	console.log(`You got it! It took you ${attempts} guesses`);
    }

    For, Of


    (No Internet Explorer Support)
    for (variable of iterable) { statement }
    const subreddits = ['cringe', 'books', 'funny', 'soccer', 'pics']
    
    for (let i = 0; i < subreddits.length; i++) {
    	console.log(`Visit reddit.com/r/${subreddits[i]}`)
    }
    
    for (let sub of subreddits) {
    	console.log(`Visit reddit.com/r/${sub}`)
    }
    for (let row of seatingChart) {
    	for (let student of row) {
        	console.log(student);
        }
    }
    for (let char of "hello world") {
    	console.log(char)
    }
    

    Iterable objects


    testScores {kim:89, vonnie:60, dwayne:77, shawn:91}
    Object.keys(testScores)
    Object.values(testScores)
    Object.entries(testScores)
    スコアの表示
    for (let person in testScores) {
    	console.log(`${person} scored ${testScores[person]}`);
    }
    平均値を求める
    let total=0;
    for (let score of Object.values(testScores)) {
    	total+= score;
    }
    console.log(total / scores.length)

    To do list project

    let input = prompt('what would tou like to do?');
    const todos = ['collect eggs','clean litter box'];
    while (input !== 'quit' && input !== 'q') {
    	if (input === 'list') {
        	console.log('***********')
            for (let i = 0; i < todos.length; i++) {
                console.log(`${i}: ${todos[i]}`);
            }
            console.log('***********')
        } else if (input === 'new') {
        	const newTodo = prompt('what is the new todo');
            todos.push(newTodo);
            console.log(`${newTodo} added to the list`)
        } else if (input === 'delete') {
        	const index = parseInt(prompt('enter the index'));
            if (!Number.isNaN(index)) {
            	const deleted = todos.splice(index, 1);
            	console.log(`ok, deleted ${deleted[0]}`);
            } else {
            	console.log('unknown index')
            }
        }
        input = prompt('what would you like to do?')
    }
    console.log('ok.quit the app')
    

    ⭐️⭐️⭐️ Function



    function functionName() { }
    function greet(person) {
    	console.log(`Hi, ${person}!`);
    }
    person -> parameter
    
    greet('Tim')
    Tim -> argument
    
    function repeat(str, numTimes) {
    	let result = '';
        for (let i = 0; i < numTimes; i++) {
        	result += str;
        }
        console.log(result);
    }

    ->capturabl valueではありません
    function add(x,y) {
    	if (typeof x !== 'number' || typeof y !== 'number') {
        	return false;
        }
        let sum = x + y;
        return sum;
    }
    
    add(add(1,5), 9) //15
    return -> only one value, only one array
    -> stops the execution of the function
    function lastElement(item) {
        if (!item.length) return null;
        return item[item.length - 1];
    }
    ---
    function capitalize (string) {
        let fl = string.slice(0,1);
        let fl2 = fl.toUpperCase();
        let rl = string.slice(1);
        return fl2 + rl;
    }
    ---
    function sumArray(arg) {
        let total = 0;
        for (let i=0;i<arg.length; i++ ) {
            total += arg[i];
        }
        return total;
    }
    ---
    function returnDay(num) {
        let array = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        if (num < 1 || num > 7) {
            return null;
        } else {
            return array[num-1];
        }
    }

    scope


    無効
    function collectEggs() {
    	let totalEggs = 6;
    }
    
    collectEggs();
    console.log(totlaEggs);
    変数は関数の中でscopeだから!
    let totalEggs = 0;
    function collectEggs() {
    	totalEggs = 6;
    }
    console.log(totalEggs);
    collectEggs();
    console.log(totalEggs);
    これは可能ですが、使用例ではありません.
    let bird = 'a';
    function watch() {
    	let bird = 'b';
        console.log(bird);
    }
    watch() /// 'b'
    
    let bird = 'a';
    function watch() {
        console.log(bird);
    }
    watch() /// 'a'
    block
    {}
    範囲:
    ただしvarはfunctionではscopeですが、blockではscopeではありません-最近は使用されていません
    varの場合
    function scope

    block scope

    lexical scope
    function bankRobbery() {
    	const heroes = ['Spiderman','Wolverine']
        function cryForHelp() {
        	function inner() {
                for (let hero of heroes) {
                    console.log(`help us, ${hero.toUpperCase()}`)
                }
            }
            inner();
        }
        cryForHelp(); 
    }

    Fuction Expression

    const add = function(x,y) {
    	return x+y;
    }
    ⭐️ Js considers functions like any other value, like an array

    Higher order funciton


    callTwiceとcallTwiceは違います
    passing a function as an argument
    function callTwice(func) {
    	func();
        func();
    }
    
    function callTenTimes(f) {
    	for (let i = 0; i <10; i++) {
        	f()
        }
    }
    
    function rollDie() {
    	const roll = Math.floor(Math.random() * 6) +1
        console.log(roll)
    }
    
    callTenTimes(rollDie);
    callTwice(rollDie);

    Returning function

    function mystery() {
    	const rand = Math.random();
        if (rand > 0.5) {
        	return function () {
            	console.log("good")
            }
        } else {
        	return funtion() {
            aler("bad")
            }
        }
    }
    factory function
    function makeBetweenFunc(min,max) {
    	return function (num) {
        	return num >= min && num <= max;
        }
    }
    
    const isChild = makeBetweenFunc(0,18)
    const isAdult = makeBetweenFunc(19,64)
    const isSenior = makeBetweenFunc(65,120)
    
    isSenior()

    Methods

    const myMath = {
    	multiply : function(x,y) {
        	return x*y;
        },
        divide : function(x,y) {
        	return x/y;
        },
        square : function(x) {
        	return x*x;
        }
    };
    ---
    const myMath = {
    	multiply(x,y) {
        	return x*y;
        },
        divide(x,y) {
        	return x/y;
        },
        square(x) {
        	return x*x;
        }
    };
    
    myMath.square(2);
    myMath["square"](2); //안 쓰는 거
    js: array,string -> object