JS学习随记_day02

page 122:
//通过原型继承创建一个新对象
function inherit(p){
    if(p == null) throw TypeError();   //注意:typeof null => "object"(page 118描述错误抑或是我理解错误)
    if(Object.create)
        return Object.create(p);
    var t = typeof p;
    if(t != "object" && t != "function") throw TypeError();
    function f(){};
    f.prototype = p;
    return new f();
}
page 124:
//字符串访问对象属性的灵活性
var addr = "";
for(i=0; i<4; i++){
    addr += customer["address"+i] + '\n'; }
page 126:
//短路简练的常用方法,获取subtitle的length属性或undefined
var len = book && book.subtitle && book.subtitle.length;
page 128:
全局属性可以删除(在严格模式下也是如此)
"use strict";
var  x = 1;
delete this.x; // => true
6.4检测属性
js指南介绍了多种检测属性的方法

page 129:
//区分null 和 undefined
可以用 !==, ===全等来区分

page 131:
//extend({},0) 避免影响原属性

page 132:
//存取器 getter setter
var random = {
    get octet(){ return Math.floor(Math.random()*256); },
    get uint16(){ return Math.floor(Math.random()*65536); },
    get int16(){ return Math.floor(Math.random()*65536)-32768; }
};
调用方式:random.octet
set 需传参,但调用方式不明

page 135:
var book = {length:10, x:"xx"};
Object.keys(o) // => ["length","x"]返回属性数组
page 145:
var undefs = [,,] // => undefined, undefined
var arr = [1,2,] //最后的逗号可有可无
page 156:
var data = [1,2,3,4,5];
var sum = 0;
data.forEach(function(value){ sum += value; });
sum // => 15
data.forEach(function(v, i, a){ a = v + 1; });
data // => [2,3,4,5,6]
//注意forEach()没法终止,即break等没用,要想终止,必须把forEach()放try里,并能抛出一个异常。
page 157:
//filter()过滤器
a = [5,4,3,2,1];
smallvalues = a.filter(function(x){ return x<3 }); //[2,1]
everyother = a.filter(function(x,i){ return i%2==0 }); //[5,3,1]
//filter()可以用来压缩稀疏数组,因为它会跳过稀疏数组中缺少的元素
var dense = spare.filter(function(){ return true; });
page 161:
var isArray = Function.isArray || function(o){
    return typeof o === "object" &&
    Object.prototype.toString.call(o) === "[object Array]";
};
page 174:
//arguments实参列表
function max(/*...*/){
    var max = Number.NEGATIVE_INFINITY;
    for(var i=0; i<arguments.length; i++)
        if(arguments > max) max = arguments;
    return max;
}
page 176:
//将对象属性用作实参
//一种方便程序猿编写代码的代码风格
//详见js指南
page 177:
function flexisum(a){
    var total = 0;
    for(var i=0; i<arguments.length; i++){
        var element = arguments, n;
        if(element == null) continue;
        if(isArray(element))
            n = flexisum.apply(this, element);  //apply page 765, 将element数组作为实参
        else if(typeof element === "function")
            n = Number(element());
        else
            n = Number(element);
        if(isNaN(n))
            throw Error("flexisum(): can't convert "+element+" to number");
        total += n;
    }
    return total;
}

var testArr = [1,2,[4,7,8,[9,8,7]],function(){ return 999; }];
flexisum(testArr)  // => 1045
page 181:
//匿名单调(我自己取的名字)
(function(){
    //模块代码
}());  //结束函数定义并立即调用它

你可能感兴趣的:(JS学习随记_day02)