###### tags: `javascript` # Javascript Note * Why Javascript? Javascript can implement the dynamic webpage ## String ### How to print string type? ```javascript=1 // print general string in console(browser F12 console) console.log('hello'); // print string with variable const Title = 'Wall\'s Blogger'; const Author = 'Wall'; const likes = 30; let result = `The blog ${Title} by ${Author} has ${likes} likes.` console.log(result) // print html mode in console let html = ` <h2>${Title}</h2> <p>By ${Author}</p> <span>This blog has ${likes} likes.</span> `; console.log(html); ``` ### String Method ```javascript=1 let email = "wall0609@gmail.com"; let con = email.includes('!'); //Did email string have '!' character? console.log(con); // false ``` ## Array ### Array Method ```javascript=1 let NBA =['wall','doncic','curry','henton']; let res = NBA.indexOf('henton'); // return the index of array element console.log(res); ``` ## Variable recommended use `let` `const` ### variable scope ```javascript=1 let age = 30; if(true){ let age = 50; console.log('inside first code block:',age); // 50 } console.log('outside code block:',age); // 30 ``` ### var It's easily and accidentally to change the global value. But it make people hard to debug. property:can repeat declare,The scope is not restricted to block scope. ### let Can declare first and give value later. The scope is in the block,once leaving {} () ,it will be undefined. property:cannot declare same variable at the same block ### const Most properties are same as `let`. The only different is you need to give value when initializing `const`. And you cannot change the value anymore. property:declare and give value at the same time for example: ```javascript=1 const PI = 3.14159 ``` --- ## Function ### function declaration & expression ```javascript=1 function greet(){ // declaration console.log('hello wall!'); } greet(); //expression ``` ### another declare way ```javascript=1 const speak = function(name = 'wall',time = 'night'){ console.log(`good ${time} ${name}`); }; speak('doncic','morning'); // change the parameter value // good morning doncic speak(); // use default value // good night wall ``` ### compare regular & arrow function ```javascript=1 // regular function const calcArea = function(radius){ return 3.14 * radius**2; } // arrow function const calcArea = (radius) =>{ return 3.14 * radius**2; }; // one line arrow function const calcArea = radius => 3.14 * radius**2; ``` ## forEach array ### read array values (function) ```javascript=1 let players = ['Doncic','Wall','Kyrie','James']; // forEach is method players.forEach(function(player,index){ // contain regular function console.log(player,index+1); console.log(`${index} - hello ${player}`); }); players.forEach((player,index) =>{ // contain arrow function console.log(player,index+1); }); ``` ### method with function ```javascript=1 let players = ['Doncic','Wall','Kyrie','James']; const loginPerson = function(player,index) { console.log(player,index+1); console.log(`${index} - hello ${player}`); } //forEach : method , loginPerson : function players.forEach(loginPerson); ``` ### show data in html use innerHTML add html tag to show some data get from array the function of document.querySelector is query css selector . ==> class # ==> id ex. .people means the tag which class="people" ```javascript=1 const ul = document.querySelector('.people'); const people = ['mario','doncic','wall','curry']; let html = ``; people.forEach(function(person){ html +=`<li style= "color:purple" >${person}</li>`; }); ul.innerHTML = html; ``` ## object type ```javascript=1 const blogs = [ { title: 'who am I' , likes: 30 }, { title: 'Just do it' , likes: 50 }, ]; ``` ```javascript=1 let user = { name: 'wall', age: 25, email: 'wall0609@gmail.com', location: 'Taipei', blogs: [ { title: 'who am I' , likes: 30 }, { title: 'Just do it' , likes: 50 }, ], login: function(){ console.log('the user loggeg in'); }, logout: function(){ console.log('the user loggeg out'); }, logBlogs(){ // regular function console.log('the following blogs:'); this.blogs.forEach(blog => { // arrow function console.log(blog.title,blog.likes); }); // not recommand use arrow function with 'this' key word } }; console.log(user); // print all info console.log(user.location); //Taipei console.log(user['email']); // 'wall0609@gmail.com' console.log(typeof user); //object user.login(); //this is object function user.logout(); // print `the user loggeg out` user.logBlogs(); const MyName = 'wall'; console.log(MyName.toUpperCase()); // javascript string method ``` ### Math object introduce Math object ```javascript=1 console.log(Math); // show all propreties in Math object console.log(Math.PI); // 3.14... // the function declare inside the object console.log(Math.E); ``` use the proprety of Math object ```javascript=1 const area = 7.7; console.log(Math.round(area)); // 四捨五入 console.log(Math.floor(area)); // 無條件捨去 console.log(Math.ceil(area)); // 無條件進位 console.log(Math.trunc(area)); //Math.trunc() function returns the integer part of a number by removing any fractional digits. const random = Math.random(); console.log(random); // 0~1 random console.log(Math.round(random * 100)); // create int random ``` ## primitive type v.s. reference type primitive type store in stack reference type store in heap copy reference type will not copy the pointer , it will point at same object. ### primitive type 1. Boolean 2. null 3. undefined 4. String 5. Number ```javascript=1 let scoreOne = 50; let scoreTwo = scoreOne; // copy scoreOne value and it is an individual // Now there are two 50 in the stack console.log(`scoreOne:${scoreOne}`,`scoreTwo:${scoreTwo}`); // 50 , 50 scoreOne = 60; console.log(`scoreOne:${scoreOne}`,`scoreTwo:${scoreTwo}`); // 60 , 50 ``` ### reference type 1. Array 2. Function 3. Object ```javascript=1 const userOne = {name: 'wall' , number: '2'}; const userTwo = userOne; // userTwo create a pointer which point to userOne objeect console.log(userOne,userTwo); // same value userTwo.number = 1; console.log(userOne,userTwo); // same value number:'1' ``` ## Class 物件導向的 JavaScript 有兩種方式可以建構物件 * 構造函數 * 類別 ### 構造函數 ```javascript=1 function CreateCard(initName){ this.name = initName; } const card = new CreateCard('wall') // 用構造函數建構新物件 console.log(card); // wall ``` ### class ```javascript=1 class Card { constructor(initName) { this.name = initName; //this.hellooo = this.hello.bind(this); // binding this on Card class(object) } hello(){ console.log('hello',this.name); } bye =()=> { // arrow function console.log('byebye',this.name); } } const c1 = new Card('doncic'); c1.hello(); // hello doncic ``` #### this : 隸屬於所在的block * this 放在所有 block 外,變成全域物件,在瀏覽器之下則隸屬於 window * arrow 形式的 function 不為一個 block * 可以將 this 綁定在想要的物件上 ex. this.hellooo = this.hello.bind(this); ```javascript=1 const a = {name: 'wall'}; a.hellooo = c1.hello; // this 隸屬於 a 因此取物件 a 的值 a.hellooo(); // hello wall ``` because arrow function not a block , this in c1.bye is belong to c1 (Card) object ```javascript=1 const b = {name: 'curry'}; b.byebyebye = c1.bye; // Card c1 function bye() b.byebyebye(); // byebye doncic ``` ## Inheritance (class) ```javascript=1 class Car{ // parent constructor(initName){ this.name = initName; } start(){ // function console.log('車子啟動'); } } class Toyota extends Car{ // Toyota(son) Inheritance Car(parent) constructor(nameToyota){ // 建構子 super(nameToyota); } start2(){ super.start() console.log('車子停止'); } } const t1 = new Toyota("MyToyota"); console.log(t1.name); // super // MyToyota ``` ## DOM tree ### getElement ```javascript=1 // querySelectorAll : query all tag include attribute const errors = document.querySelectorAll('.error'); errors.forEach(error => { console.log(error); }); // get one Tag by id const title = document.getElementById('page-title'); console.log(title); // get all Tag by class const err = document.getElementsByClassName('error'); console.log(err); // HTML Collection Type // cannot use forEach function // get all Tag by tag const tags = document.getElementsByTagName('p'); console.log(tags); console.log(tags[0]); // first p tag html ``` ### innerHTML proprety it contains one or some html tags And it will cover the original content if you change its innerHTML ```javascript=1 <div> <p>hello</p> innerHtml is <p>hello</p> </div> ``` ### innerText proprety only contain text(visibility) not include tag ```javascript=1 const link = document.querySelector('a'); link.innerText = "Link to Facebook."; ``` ### textContent `textContent` can get all text , even hidden text the following method can check the content and change html style ```javascript=1 const paras = document.querySelectorAll('p'); paras.forEach(p => { if(p.textContent.includes('error')) { // wall curry doncic (no error) p.classList.add('error'); // then class="error" } if(p.innerText.includes('success')){ p.classList.add('success'); } }) ``` ### getAttribute ```javascript=1 const link = document.querySelector('a'); console.log(link.getAttribute('href')); // https://google.com ``` ### setAttribute This method can change or set the new attribute ```javascript=1 link.setAttribute('href','https://facebook.com'); link.setAttribute('style','margin:50px;'); // use setAttribute it will cover the old style value ``` But `setAttribute` will cover the old style value If you want to add more style values in style You can try this way ```javascript=1 mssg.style.margin = '50px'; mssg.style.fontSize = '30px'; // font-size == fontSize mssg.style.margin = ''; // '' represent empty margin value ``` ### classList `classList` can get the all class name of tag ```javascript=1 console.log(mssg.classList); //class="btn btn_primary" mssg.classList.add('error'); // add error class name mssg.classList.remove('error'); // remove error class name ``` classList toggle(切換) method ```javascript=1 title.classList.toggle('text'); // 有則 remove title.classList.toggle('text'); // 沒有則 add ``` ### addEventListener When we decide to use javascript in html DOM,first we need to listen to all elements. Why? Because if one of the elements has been clicked,we will give the webpage some action by javascript code. Therefore we should load all elements to make sure the DOM structure has been create completely. addEventListener 監聽 load 載入頁面 function 回呼函數(load成功後執行函數) ```javascript=1 window.addEventListener(‘DOMContentLoaded’,function(){ // some action }); ``` There are many actions in javascript,now we choose some function to show what javascript can do. --- When a user clicks the specific button it will do the corresponding action. ```javascript=1 responsiveNavItem.addEventListener('click', () => { if (window.getComputedStyle(navbarToggler).display !== 'none') { navbarToggler.click(); } }); ``` Change text color or record every keyup value ```javascript=1 window.addEventListener('load',function(){ console.log('load'); const input1 = this.document.getElementById('input1') const text = this.document.getElementById('change') const btn = this.document.getElementById('clickme') btn.addEventListener('click',function(){ console.log("click click"); text.style.color = "red"; }); // every keyup print every value input1.addEventListener('keyup',function(e){ console.log(e.target.value); }) }) ``` getComputedStyle can get all css attribute from the element(here is navbarToggler element) --- addEventListener first parameter can listen a lot of action. For example : `load` `click` `keyup` 等等... ```javascript=1 addedBtn.addEventListener("click", function(){ myForm.style.display = 'block'; addedBtn.style.display = 'none'; }); ``` ## Event.target `event.target` 屬性永遠指向觸發事件的 DOM 物件 `event.target` 就是指事件發生位置