1. 程式人生 > 其它 >JS ES6學習筆記

JS ES6學習筆記

// For應用---------------------------------------------

const todos = 
[
    {
        id          : 1,
        text        : 'Take out trash',
        isCompleted : true
    },
    {
        id          : 2,
        text        : 'Meeting with boss',
        isCompleted : true
    },
    {
        id          : 3,
        text        : 'Dentist appt',
        isCompleted : false
    },
];
for(let i=0; i<todos.length; i++)
{
    console.log('todos[i].text:', todos[i].text);
}
//簡潔用法
for(let t of todos)
{
    console.log('t.id:',t.id);
}
// forEach, map, filter--------------------------------------------
// forEach
todos.forEach   //也可以寫成箭頭函式
(
    function(t) // 這是回撥函式
    {
        console.log('t.text:', t.text);
    }
);
// map
const t = todos.map   //map返回一個數組
(
    function(t)
    {
        // console.log('t.text:', t.text);
        return t.id === 1;
        // return t.id;
    }
);
console.log('t:', t);
// filter 過濾器
const tCompleted = todos.filter  //Completed 完整的
(
    function(t)
    {
        return t.isCompleted === true; // === 相當於python的 ==
    }
);
console.log('tCompleted:', tCompleted)
// map和filter的區別:前者是返回陣列,後者是返回符合條件的陣列

const tttCompleted = todos.filter   
(
    function(t)
    {
        return t.isCompleted === true;
    }
).map(function(t){return t.text;})
console.log('tttCompleted:', tttCompleted)
// javascript常用變數型別: // Numbers, String, Boolean, Object: Array, Undefined, Null
const name   = 'John'; // String
const age    = 22;     // Numbers
const rating = 4.5;    // Numbers, 沒有浮點型別,只是數字
const isCool = true;   // Boolean
const x      = null;   // Object
let z        = [1,2,3];  //Object
const y      = undefined; // undefined
/* let和const的 共同點是:1、不可重複宣告 2、都是程式碼塊作用域 不同點是:const是常量,定義賦值後,不可改變 var與let、const特性完全相反 */ // 邏輯運算演示--------------------------------------------------- // falseundefined, 0, "", null, false // true 是 除了上面的,都是true
// ----------- || 或    演示 -----------
const xx = 11;
if(xx<6 || xx>10) // ||某一個是true,結果為true
{
    console.log('邏輯‘或’:成立')
}else
{ console.log('邏輯‘或’:不成立') }


// ----------- && 與    演示 -----------
const yy = 11;
if(yy>1 && yy<10) // &&需要兩個條件都是true,結果才是true
{
    console.log('邏輯‘與’:成立')
}else
{ console.log('邏輯‘與’:不成立') }


// 三元操作符 --------------
const xxx = 9;
const color = xxx > 10 ? 'red' : 'blue'; 
//如果問號後面條件為真,設定color為red,冒號代表else
console.log('xxx color :', color)