2017年5月26日 星期五

(js)編寫含式變項,常會遇到的問題

function test_1() {
            var data = {};

            var y;
            if(data.age){
                    y = data.age;
            }else{
                y = 5
            }

            alert(y);
        }

        function test_2() {
            var data = [];

            var y;

             if(data[0]){
                 y = data[0];
             }else{
                 y = 5;
             }

            alert(y);
        }

function test_3() {           
            var data;

            var y;

            // 以下不行
            if(data.age){
                    y = data.age;
            }else{
                y = 5
            }

            alert(y);
        }