• javascript tips and snippets


    • 如何给javascript对象动态创建动态key

    // ES2015
    var key = 'DYNAMIC_KEY',
        obj = {
            [key]: 'ES6!'
        };
    
    console.log(obj);
    // > { 'DYNAMIC_KEY': 'ES6!' }
    
    // NON ES2015
    var obj = [];
    obj[0] = "hello world";
    obj["something"] = 5000;
    
    var objJSON = JSON.stringify(obj);
    • 数字化的Date

    js中,Date是内置的一种数据类型,虽然直接输出的date格式适合人们阅读,但是对于机器程序来说却有些不方便:

    var now=new Date();
    console.log(now);//Wed Nov 25 2015 22:02:17 GMT+0800 (中国标准时间)

    怎么转换为便于js程序来操作的形式呢?很简单只要在new关键字前面加上一个+即可:

    var now=+new Date();
    console.log(now);//1448460291345

     javascript Errors: try{}catch(){}的重要性

    在JS APP中,对于一些很有可能会出错的代码,强烈建议使用try{}catch(){}的方式来调用,否则会出现一个错误就导致app crash的问题。相信crash并不是你想要的状态,你可能希望出错没有关系啊,下次出错的条件解除了,我们希望程序能够继续运行,这就必须使用try catch的模式来写可能出错的代码,允许出错

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    try {
      foo.bar();
    } catch (e) {
      if (e instanceof EvalError) {
        alert(e.name + ': ' + e.message);
      } else if (e instanceof RangeError) {
        alert(e.name + ': ' + e.message);
      } else if (e instanceof InternalError) {
        alert(e.name + ': ' + e.message);
      }else if (e instanceof ReferenceError) {
        alert(e.name + ': ' + e.message);
      }else if (e instanceof SyntaxError) {
        alert(e.name + ': ' + e.message);
      }else if (e instanceof TypeError) {
        alert(e.name + ': ' + e.message);
      }else if (e instanceof URIError) {
        alert(e.name + ': ' + e.message);
      }
      // ... etc
    }

     Javascript小数点问题

    由于javascript使用浮点数来运算小数,而小数总归会有一定的精确度,所以往往出现一些比较怪异的问题:

    console.log(0.1+0.2);//0.30000000000000004
    console.log((0.1+0.2).toFixed(2));//0.30
    (0.1+0.2)==0.3 //false!!!!
    (0.1+0.2).toFixed(1)==0.3 //true!!!
    (0.1+0.2).toFixed(2)===0.3 //flase!!! 原因是toFixed(2)调用后实际上返回的是"0.30"

    在上面的代码,由于toFixed将返回一个字符串,所以使用===来比较,则返回false;再看下面的代码:

    function tax(price,percent){
      return parseFloat((price*percent/100).toFixed(2));
    }
    var myprice = 9;
    var taxpercent =70;
    var total = myprice+tax(myprice,taxpercent);
    console.log(total.toFixed(2)); //"15.30"

    javascript hoisting

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    var x = 5;  // Initialize x
    
    elem = document.getElementById("demo");            // Find an element 
    elem.innerHTML = "x is " + x + " and y is " + y;    // Display x and y==> x is 5 and y is undefined,虽然y是declared了(due to hoisting),但是却没有defination未定义
    
    var y = 7;  // Initialize y
    </script>
    
    </body>
    </html> 

    modula Pattern

    var ARMORY =(function(){
        var weaponList = [*list of weapon objects*];
        var armorList = [*list of armor objects*];
    
        var removeWeapon = function(){};
        var replaceWeapon = function(){};
        var removeArmor = function(){};
        var replaceArmor = function(){};
    
        return {
            makeWeaponRequest: function(){};
            makeArmorRequest: function(){};
        };
    
    })();
    ARMORY.makeWeaponRequest('Excalibur');

    上面这段代码中,使用IIFE调用后返回一个global object ARMORY作为namespace,暴露两个public函数公外部调用,内部的local data都已经被封装起来, 

    通过ARMORY.makeWeaponRequest()函数调用,来通过private函数removeWeapon又去访问namespace的local variable weapList,删除相应武器数据后,可能返回一个weapon列表对象的copy到ARMORY.makeWeaponRequest的scope中去使用。

    Import Globals into IIFE

    在上面的module pattern中,如果需要访问一个全局变量,比如我们添加一个指示是否正在战争游戏的flag,在makeWeaponRequest函数中,我们根据这个flag来做特定的动作,那么可行的方法是将wartime这个flag作为IIFE的参数传入:

    var wartime = true;
    var ARMORY =(function(war){
        var weaponList = [*list of weapon objects*];
        var armorList = [*list of armor objects*];
    
        var removeWeapon = function(){};
        var replaceWeapon = function(){};
        var removeArmor = function(){};
        var replaceArmor = function(){};
    
        return {
            makeWeaponRequest: function(){
                if(war) //let civilians have weaponry
    
            };
            makeArmorRequest: function(){};
        };
    
    })(wartime);
    ARMORY.makeWeaponRequest('Excalibur');

    在上面这个pattern中,需要注意的是wartime作为参数传入了IIFE虽然意味着IIFE中能够方便的访问到wartime的数据拷贝,但是如果外部的环境发生变化了,后续再调用makeWeaponRequest时,无法感知!@!原因是war这里是wartime的一个copy,并不是直接引用!

    当然,如果希望内部和外部完全同步,有一个可行的方法是,将wartime声明为一个object或者array,在IIFE内部通过 object.property,array[index]方式来读或者写就可以实现内外完全同步了!看下面的简单说明:

    function replace(ref) {
        ref = {};           // this code does _not_ affect the object passed
    }
    
    function update(ref) {
        ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
    }
    
    var a = { key: 'value' };
    replace(a);  // a still has its original value - it's unmodfied
    update(a);   // the _contents_ of 'a' are changed

     文字盒翻滚效果

    var wordBox = $("#theWords");
        var timer;
    
        timer = setTimeout(function(){
    
            var argCallee = arguments.callee;
    
            var fSpan = $("#theWords span:first");
            
            fSpan.animate({
                marginTop:-20
            },500,function(){
                wordBox.append(fSpan);
                fSpan.css("margin-top","0");
                timer = setTimeout(argCallee,3000);
            });
            
        },3000);
    html:
    <div id="theWords" class="theScrollword">      <span style="margin-top: 0px;">不怕做不到只怕想不到。</span><span style="margin-top: 0px;">学而不思则罔!</span><span style="margin-top: 0px;">思而不学则殆 </span><span style="margin-top: 0px;">我听我忘,我看我会,我做我懂 </span><span style="margin-top: 0px;">做个有价值的人。</span></div>
    css:
    .theScrollword {
        height: 20px;
        overflow: hidden;
        position: relative;
        margin: 20px 0 0;
        padding: 0 0 0 40px;
        float: left;
        display: inline;
    }
    .container .toparea .notice span {
        text-align: left;
        color: #fffeff;
        font-size: 14px;
        display: block;
    }

    上面一段代码的原理是使用jquery的animate函数对第一个span的margin-top属性来做动画,并且不断将第一个span移动到最后去

    jquery document ready and window load

    我们知道javascript在操作一个页面的元素时,必须保证document is "ready"。 jQuery侦测readiness状态。在$(document).ready()函数中的代码只有在页面的Document Object Model(DOM)完全就绪后才会被执行(而对于未定义在ready handler中的javascript代码则基本上会在DOM完全构建完成之前运行!!!)。而在$(window).load(function(){...})中的代码则只有整个page的资源(images,css,iframes)都加载完成(或者timeout failure)后才被运行,而不是DOM一就绪就运行;

    DOM就绪发生在HTML Document被浏览器接收(注意对应的JS也被加载运行了!!),并且解析成对应的DOM数后发生!。看看下面的示例代码:

    <html>
    <head>
        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script>
        $( document ).ready(function() {
            console.log( "document loaded" );
        });
     
        $( window ).load(function() {
            console.log( "window loaded" );
        });
        </script>
    </head>
    <body>
      <img src="http://xx.yy.com/build/images/internet.jpg" />
        <iframe src="http://techcrunch.com"></iframe>
    </body>
    </html>

    上面的代码将首先打出“document loaded”,随后在img,iframe全部加载完成后,打印出"window loaded"

    列出所有全局空间的对象

    有时我们希望看到在我们的页面上有哪些可以操作的全局对象,通过Object.keys(window)就可以轻松实现。更进一步,我们希望打印出对象,并且方便检视,则可以使用下面的代码:

    (function ()
    {
       var keys=Object.keys( window );
       for (var i in keys)
       {
          if (typeof window[keys[i]] != 'function')
          console.log(keys[i], window[keys[i]]);
       }
    })();

    函数柯里化充分理解闭包,返回函数的概念

    function add(value) {
        var helper = function(next) {
            console.log("value is: "+ value + "--line 481" );
            value = typeof(value)==="undefined"?next:value+next;
            console.log("value is: " +value + "--line 483");
            return helper;
        }
        helper.valueOf = function() {
            console.log("valueOf is called at 488");
            return value;
        }
        return helper;
    }   
    console.log(add(2)(3)(5)(7));

    value is: 2--line 481
    value is: 5--line 483
    value is: 5--line 481
    value is: 10--line 483
    value is: 10--line 481
    value is: 17--line 483
    jstext.html:495 17
    valueOf is called at 488

    注意:valueOf是console.log(returnHelper)时js引擎自动会调用returnHelper.valueOf方法的~~~!

    如何reset input file控件的选择状态以便能够再次选择同一文件?

    input file控件在首次选择文件后,如果我们取消remove掉了所选文件,后面突然反悔又希望再次选中同一个文件,由于该控件具有一个内在的逻辑是由于选过,不允许重复选择,因此选择无效,这时,一个简单有效的方法是通过javascript设置该空间的type属性

    input.type = ''
    input.type = 'file'

     javascript中的数组操作方法

    在javascript中对数组的操作总体上分为两类:一种是mutation的也就是执行对应函数后原数组将会被修改,一种是accessor,就是返回源数组的部分数据,不会对原数组做任何的修改。

    mutation类的函数有: 

    array.reverse, array.splice, array.shift, array.unshift, array.sort

    accessor类的函数有 

    array.concat, array.indexOf, array.join, array.lastIndexOf, array.slice 

    javascript regex正则

    https://javascript.info/regexp-methods

  • 相关阅读:
    用谷歌浏览器来模拟手机浏览器
    手机端网页设计尺寸,手机端网页设计图片尺寸
    响应式web网站设计制作方法
    css3媒体查询实现网站响应式布局
    MVC框架是什么
    ExecutorService与ThreadPoolTaskExecutor
    JSONObject、JSONArray区别
    redis 的理解
    redis 下载及使用
    springBoot上传文件大小设置
  • 原文地址:https://www.cnblogs.com/kidsitcn/p/4996101.html
Copyright © 2020-2023  润新知