Upgrade to Pro — share decks privately, control downloads, hide ads and more …

社内勉強会資料 JavaScriptの基本 その1

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

社内勉強会資料 JavaScriptの基本 その1

社内勉強会用の資料

Avatar for shmurakami

shmurakami

April 11, 2014
Tweet

More Decks by shmurakami

Other Decks in Programming

Transcript

  1. 予想外の挙動 <script> var localStorage = 'file'; console.log(localStorage); // Storage{length: 2}

    </script> // localStorageͱ͍͏໊લͰఆٛͰ͖ͨΓ // ఆٛࡁΈͷม਺Λ্ॻ͖Ͱ͖ͳ͔ͬͨΓ ؀ڥʹΑͬͯڍಈ͕ҟͳΔ
  2. var i, l = 0; console.time('global'); for (i=0;i<1000000;i++) {l++} console.timeEnd('global');

    (function(){ var m, n = 0; console.time('local'); for (m=0;m<1000000;m++) {n++} console.timeEnd('local'); })(); そもそも遅い ≒2.3ms ≒5ms
  3. var hoge = 'hoge'; console.log(hoge); if (false) { var fuga

    = 'fuga'; } console.log(fuga); // undefined console.log(piyo); // ReferenceError: Can't find variable: piyo <?php $hoge = 'hoge'; echo $hoge; if (false) { $fuga = "fuga"; } echo $fuga; // Notice: Undefined variable: fuga 変数の巻き上げ PHP JS
  4. // ࣮ߦ࣌ͷΠϝʔδ var hoge, fuga; hoge = 'hoge'; console.log(hoge); if

    (false) { fuga = 'fuga'; } console.log(fuga); // undefined console.log(piyo); // ReferenceError: Can't find variable: piyo var hoge = 'hoge'; console.log(hoge); if (false) { var fuga = 'fuga'; } console.log(fuga); // undefined console.log(piyo); // ReferenceError: Can't find variable: piyo JS実行時のイメージ
  5. Number ͢΂ͯഒਫ਼౓ුಈখ਺఺਺ JOUͳΜͯແ͔ͬͨ খ਺ԋࢉΛ͢Δͱ஋͕ͣΕΔ͜ͱ͕͋Δ (1.5 - 1) / 2 =

    0.25 (1.4 - 1) / 2 = 0.1999999999999996 ! (((1.4*10) - (1*10)) /10)/2 ͱ͠ͳ͖Ό ͍͚ͳ͍
  6. String型の数値の大小比較 10 > 2 // true “10” > “2” //

    false // numberͷͭ΋ΓͰstringͷେখΛൺֱͯ͠͠·͏ͱ ҙਤ͠ͳ͍ڍಈʹͳΔɻ // ܕΛҙࣝ͢Δ͜ͱ
  7. jQueryの注意点                    

    ※とりあえず1番気になっててやめて 欲しいことだけ
  8. 対策: 変数に入れる <p id=”hoge”>ͺΒ͙Β;</p> <button id=”btn”>Ϙλϯ</button> $('#btn').click(function() { var hoge

    = $(‘#hoge’); hoge.css('color', '#f00'); hoge.css('width', '200px'); hoge.text('paragraph'); });
  9. var btn = $('btn'); console.time('var'); for (var i = 0;

    i < 100000; i++) btn.val('btn'); console.timeEnd('var'); console.time('selector'); for (var i = 0; i < 100000; i++) $ ('#btn').val('btn'); console.timeEnd('selector'); 比較した ≒900ms ≒90ms 変数の方が10倍速い
  10. $(function () { var i; for (i=0; i<10000; i++) {

    $('#hoge').css('width', '200px').css('color', '#f00').text('p'); } }); $(function () { var i; for (i=0; i<10000; i++) { var hoge = $('#hoge'); hoge.css('width', '200px'); hoge.css('color', '#f00'); hoge.text('p'); } }); メソッドチェーン 変数 610.54ms 624.8 ms
  11. HTMLのインラインに書かない <html> <head> </head> <body> <script> // .... // ....

    // .... </script> </body> </html> ΠϯϥΠϯʹॻ͘ͱ Ωϟογϡ͞Εͣʹ ຖճDL͞ΕΔ