[JavaScript] 자주 쓰이는 함수

[JavaScript] 자주 쓰이는 함수

var integerNum = parseInt(str); // string--> integer var binaryNum = parseInt(str, 2); //binary number라는 것을 컴퓨터에게 알려줌

num > 0 ? "positive" : num < 0 ? "negative" : "zero"; if(num > 0){ return "positive"; } else if(num < 0){ return "negative"; } else{ return "zero"; }

"use strict"

//var와 let 차이 function checkScope(){ "use strict"; var i = "function scope"; if(true){ i = "block scope"; console.log("block scope i is : ",i); } console.log("function scope i is : ",i); return i; } checkScope(); //block scope //block scope function checkScope(){ "use strict"; let i = "function scope"; if(true){ let i = "block scope"; console.log("block scope i is : ",i); } console.log("function scope i is : ",i); return i; } checkScope(); //block scope //function scope function checkScope(){ "use strict"; //let i = "function scope"; if(true){ var i = "block scope"; console.log("block scope i is : ",i); } console.log("function scope i is : ",i); //can still access return i; } checkScope(); //block scope //block scope function checkScope(){ "use strict"; //let i = "function scope"; if(true){ let i = "block scope"; console.log("block scope i is : ",i); } console.log("function scope i is : ",i); //can not access return i; } checkScope(); //block scope //not defined //var는 블록 밖에서도 여전히 접근, 수정 가능하다. //let은 해당 블록 내에서만 사용 가능하다. ex)if, while, for //let 대신 var를 사용하는 이유.

const sentence = "hello"; //수정 불가 const s= [5,7,2]; function test(){ "use strict"; //s=[2,5,7]; s[0]=2; s[1]=5; s[2]=7; //배열 주소는 접근이 안 되고 //인덱스로 접근해야 함 } test(); console.log(s);

function freezeObj(){ "use strict"; const MATH_CONSTANTS = { PI: 3.14 }; Object.freeze(MATH_CONSTANTS); try{ MATH_CONSTANTS.PI = 99; console.log(MATH_CONSTANTS.PI); }catch(ex){ console.log(ex); } return MATH_CONSTANTS.PI; } const PI = freezeObj(); //read only error

//arrow function var myConcat = function(arr1, arr2){ return arr1.concat(arr2); } var myConcat2 = (arr1, arr2) => arr1.concat(arr2); //위 아래 같음 const real = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]; const squareList = (arr) => { const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0).map(x => x*x); return squaredIntegers; } const squaredIntegers = squareList(real); console.log(squaredIntegers); const increment = (function(){ return function increment(number, value =1){ return number+value; }; })(); console.log(increment(5,2)); console.log(increment(5)); //7 //6 const sum = (function(){ return function sum(...args){ return args.reduce((a,b)=> a+b, 0); }; })(); console.log(sum(1,2,3)); //아래와 같음 const sum = (function(){ return function sum(x,y,z){ const args = [x,y,z]; return args.reduce((a,b)=> a+b, 0); }; })(); console.log(sum(1,2,3));

from http://mumumi.tistory.com/157 by ccl(A) rewrite - 2021-10-06 18:01:07