Tag: dependency

  • JS-運算元Operands、運算子Operator、優先性Precedence、相依性Associativity

    參考資料: MDN Web, 六角學院

    運算子優先序(Operator precedence)決定了運算子彼此之間被語法解析的方式,優先序較高的運算子會成為優先序較低運算子的運算元(operands)。

    請給予肝肝的工程師一些支持! 'W'

    <運算式與運算子/條件運算子>

    摘錄:

    條件 (三元) 運算子 是 JS唯一用到三個運算元的運算子:在一個條件後面會跟著一個問號 (?),如果條件是 true,在冒號(:)前的表達式會被執行,如果條件是 false,在冒號後面的表達式會被執行,這個運算子常常被用來當作 if 的簡潔寫法.

    function getSalary(isMember) {
      return (isMember ? '$3600.0' : '$4000.0');
    }
    
    console.log(getSalary(true));
    // expected output: "$3600.0"
    
    console.log(getSalary(false));
    // expected output: "$4000.0"
    
    console.log(getSalarye(null));
    // expected output: "$4000.0"

    3600.0 //運算元

    4000.0 //運算元

    運算子語法結構>>

    condition ? exprIfTrue : exprIfFalse

    參數

    condition
    • 值用來做為條件的表達式
    exprIfTrue
    • 如果 condition = trueexprIfTrue 會被執行
    exprIfFalse
    • 如果 condition =falseexprIfFalse 也會被執行

    <優先性>

    先乘除後加減->>

    var valueA =3*2 + 4*3
    var valueB =4*(3*8)
    console.log(valueA,valueB);
    
    // output: 18,96
    
    console.log(3 + 4 * 5); // 3 + 20
    // output: 23
    
    console.log(4 * 3 ** 2); // 4 * 9
    // output: 36
    
    let a;
    let b;
    
    console.log(a = b = 5);
    // expected output: 5

    相依性-由左邊到右邊判斷>>>

    剛剛我們說到了Javascript 遵從先乘除後加減規格, 但我們仍然試圖找尋這些奇怪的地方。這裡很需要各位的拆解能力。
    console.log(1>2>3);
    console.log(3>2>1);

    不要急, 慢慢想!

    不要這麼輕易的就看答案!

    .

    .

    .

    .

    .

    .

    .

    答案揭曉

    神奇的事情發生了~

    console.log(1>2>3);
    console.log(3>2>1);
    // true 
       false
    3>2  //這裡就會變成true
    true > 1 // 按照通識觀念, 這一定會是false。

    表達式賦予值>>

    Object.defineProperty() 用法參考這!

    • The static method Object.defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
    // 物件
    var b = {};
    
    //宣告物件.屬性
    Object.defineProperty(b,'a',{
    
    value: 2,
    writable:false
    
    });
    
    b.a =3; //賦予值 3
    console.log(b.a);
    
    var a=3;
    
    a=b.a =1; //奇怪的地方喔! 
    
    console.log(a,b.a);
    // Output
       2
       1,2

    b.a =3 賦予值, 但是 Object.defineProperty 屬性內是不可更改 = “writable: false”

    a=b.a =1; //奇怪的地方喔!

    走啊! 回去翻翻 JS表達式的特性 文章, 你將會知道答案。
    // 物件
    var b = {};
    
    //宣告物件.屬性
    Object.defineProperty(b,'a',{
    
    value: 2,
    writable:false
    
    });
    
    b.a =3; //賦予值 3
    console.log(b.a);
    
    var a=3;
    
    a=b.a =1; //奇怪的地方喔! 
    
    console.log(a,b.a);
    // Output
       2
       1,2

    我們再建立另外一個物件.屬性

    Object.defineProperty() 用法參考這!

    var b = {};
    Object.defineProperty(b,'a',{
    value: 2,
    writable:false
    });
    
    Object.defineProperty(b,'d',{
        value: 3,
        writable:false
        });
    
    console.log(b);
    
    var a=3;
    
    a=b.d=b.a =1;// 主要是這個地方需要探討
    
    console.log(a);

    程式執行的結果如下: