Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, September 21, 2021

JavaScript 語言基礎快速介紹 (包含ECMAScript 6)


JavaScript語言基本例子

var usr = "danny", age = 18;

//ECMAScript 6, ES 6
const LED_PIN = 13; //宣告常數, 不能修改

//primitive type
//Boolean: true or false
//Number: 3.14
//String: "AAA"
//Null: null
//Undefined: undefined

//字串轉換成數自函式
Number("8.24") -> 8.24
Number("123abc") -> NaN

parseInt("8.24") -> 8
parseInt("123abc") -> 123

parseFloat("8.24") -> 8.24
var num = 0.1 * 0.2;
num.toPrecision(12) //精確度縮限制小數點12位

//嚴格相等運算子 ===
// 8 === "8"=> false
// 8 == "8" => true 

x = ( x === undefined) ? 0 : x;

//在函式內以var宣告的變數, 都是區域變數, 以外定義的變數都是全域變數
//每隔5秒執行一次
window.setInterval(function() {
    // do something
    }, 5000);

//Array
var she = ["AAA", "BBB"];
var she = new Array("AAA","BBB");
var she = new Array(3); //三個元素空白陣列
var she = [];

she.push("CCC"); //後面添加新元素
she.pop(); //刪除最後一個元素並傳回
she.unshift("DDD"); //在陣列前最前面加入新元素
she.shift(); //刪除並傳回第一個元素
she.splice(1,1); //在index=1的位置刪除一個元素
she.splice(1,1, "EEE", "FFF"); //在index=1的位置刪除一個元素,並加入兩個新元素

//for迴圈
for(var i=0; i<total; i++) {
}
she.forEach( function(val) {
});

//Object
var obj = {name:"Danny", age:18};
delete obj.name; // delete指令僅能刪除物件的屬性

for( var key in obj){
    var val = obj[key];
    console.log("attr:" + key + ",value:" + val); 
}