晴明的博客园 GitHub      CodePen      CodeWars     

[js] 积累 (old)

奇巧淫技:

~number   取反并减1  

~~number   可实现 Math.floor()的效果

!!number  如果为0则为false,其他数值为true

ES6:(...参数)可将多个参数转成数组形式,省去了[].slice.call(arguments) 

#

this 是个参数,普通的函数调用隐式传入 this,call 和 apply 可以显式指定它。

window是所有对象的容器,document是DOM对象容器,window包含document 。

typeof null   为 object 。

var a = new Array(10);//只有一个参数的时候指定数组的长度。

如果对数组元素直接使用delete,其实并没有删除,只是将元素置为了undefined。数组元素删除应使用splice。

直接把一个数组赋值给另外一个数组,称 浅复制,新数组仍然向原来的数组。

将原数组中的每个元素都复制一份到新数组则为 深复制。

            arguments.callee
            指向当前执行的函数。
            arguments.length
            指向传递给当前函数的参数数量。 

 

#

        //unicode 转换二进制
            var fromString = function(data) {
                var i;
                var binary = '';
                var charCode;
                for (i = 0; i < data.length; i++) {
                    charCode = data.charCodeAt(i).toString(2);
                    //console.warn(charCode);
                    binary += new Array(8 - charCode.length + 1).join(0) + charCode;
                    //console.info(binary);
                }
                if (binary.length > 20) {
                    return binary.substr(0, 20) + '\u2026';
                }
                return binary;
            }
            console.log(fromString('wtf'));
            console.log([0].join(0));
            console.log([1].join(0));
            console.log([2].join(0));
            console.log([2,1,3].join(0));
            console.log([2,3].join(0));
            console.log([].join(0));

 #实例化构造函数不加new会导致this 映射到 window 上

        function Person(name, age, job){
            this.name = name;
            this.age = age;
            this.job = job;
        }
        
        var person1 = new Person("Nicholas", 29, "Software Engineer");
        console.log(person1.name);     //"Nicholas"
        console.log(person1.age);      //29
        console.log(person1.job);      //"Software Engineer"

        var person2 = Person("Nicholas", 29, "Software Engineer");
        console.log(person2);         //undefined
        console.log(window.name);     //"Nicholas"
        console.log(window.age);      //29
        console.log(window.job);      //"Software Engineer"

 # scope safe constructor  作用域安全的构造函数

        function Polygon(sides){
            if (this instanceof Polygon) {
                this.sides = sides;
                this.getArea = function(){
                    return 0;
                };
            } else {
                return new Polygon(sides);
            }
        }
        
        function Rectangle(width, height){
            Polygon.call(this, 2);
            this.width = width;
            this.height = height;
            this.getArea = function(){
                return this.width * this.height;
            };
        }
        
        Rectangle.prototype = new Polygon();//prototype 重要!
        
        var rect = new Rectangle(5, 10);
        console.log(rect.sides);   //2

 

#removeEventListener

            function a() {
                console.log('click');
                document.getElementById("a").removeEventListener('click', a);
                console.log('end');
            }
            document.getElementById("a").addEventListener('click', a)

 

 

#获取所有checkbox

            var domList = document.getElementsByTagName('input')
            var checkBoxList = [];
            var len = domList.length;  
            while (len--) {    
                if (domList[len].type == 'checkbox') {  
                    checkBoxList.push(domList[len]);  
                }
            }

 

动态变化背景

document.body.style.backgroundColor = new Date().getDay()%2?'red':'blue';

 

#生成随机的字母数字字符串

            function generateRandomAlphaNum(len) {
                var rdmString = "";
                for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
                return rdmString.substr(0, len);
            }

 

#数组之间追加

            var array1 = [12, "foo", {name:"Joe"}, -2458];
            var array2 = ["Doe", 555, 100];
            Array.prototype.push.apply(array1, array2);
            //array1 值为  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100]

 

#验证是否是数字

            function isNumber(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
            }

 

#获取数组中的最大值和最小值

            var numbers = [5, 458, 120, -215, 228, 400, 122205, -85411];
            var maxInNumbers = Math.max.apply(Math, numbers);
            var minInNumbers = Math.min.apply(Math, numbers);

 

#清空数组

            var myArray = [12, 222, 1000];
            myArray.length = 0; // myArray will be equal to [].

 

#还可使用length属性截断数组

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];  
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

 

#如果把length属性变大,数组的长度值变会增加,会使用undefined来作为新的元素填充。length是一个可写的属性。

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

 

#在条件中使用逻辑与或

            var foo = 10;
            foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething(); 
            foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

 

#浮点数计算的问题

JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示,

可以通过使用toFixed()和toPrecision()解决

0.1 + 0.2 === 0.3 // is false ,实际结果0.1+0.2等于0.30000000000000004
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

 

#逗号操作符

            var a = 0;
            var b = (a++, 99);
            console.log(a); // a will be equal to 1 
            console.log(b); // b is equal to 99

 

#HTML字段转换函数

            function escapeHTML(text) {
                var replacements = {
                    "<": "&lt;",
                    ">": "&gt;",
                    "&": "&amp;",
                    "\"": "&quot;"
                };
                return text.replace(/[<>&"]/g, function(character) {
                    return replacements[character];
                });
            }

 

#

            var a;
            alert(a);// undefined
            alert(typeof a); // undefined
            alert(b); // 报错,不会alert或console.log
            console.log(a)
            console.log(typeof a)
            console.log(b)

 

#

            var a = null;
            alert(typeof a); //object

 

#

var undefined;
undefined == null; // true
1 == true;   // true
2 == true;   // false
0 == false;  // true
0 == '';     // true
NaN == NaN;  // false
[] == false; // true
[] == ![];   // true

    undefined与null相等,但不恒等(===)
    一个是number一个是string时,会尝试将string转换为number
    尝试将boolean转换为number,0或1
    尝试将Object转换成number或string,取决于另外一个对比量的类型
    所以,对于0、空字符串的判断,建议使用 “===” 。“===”会先判断两边的值类型,类型不匹配时为false。

 

#引用关系

            var a = new Object();
            a.value = 1;
            b = a;
            b.value = 2;
            console.log(a.value);//2
            console.log(b.value);//2

 

#变量提升

            var foo = 1;

            function a() {
                console.log(foo); //undefined
                var foo = 2;
                console.log(foo); //2
            }
            a();

 

#线程

            for (var i = 1; i <= 3; i++) {
                setTimeout(function() {
                    console.log(i);
                }, 0);
            };
            //4
            //4
            //4
            for (var i = 1; i <= 3; i++) {
                setTimeout((function(a) { //改成立即执行函数
                    console.log(a);
                })(i), 0);
            };
            //1
            //2
            //3

 

#创建一个长度为100的数组,并且每个元素的值等于它的下标

   ES5

Object.keys(Array.apply(null,{length:100}));

 

 

#快速判定是否为数字

isNaN(num),是数字则为false

/\d/.test(num),是数字则为true

/[^1-9]/.test(num),不是数字则为true

Number(num),不是数字则为NaN

posted @ 2016-03-26 23:11  晴明桑  阅读(265)  评论(0)    收藏  举报