Date、Function、Number、String

博客分类: 原创

Date、Function、Number、String

##Date

###创建

创建一个日期对象通常使用如下方式,得到一个日期对象,该类型使用自UTC(Coordinated Universal Time,国际协调时间) 1970年1月1日午夜(零时)开始经过的毫秒数来保存日期。

var now = new Date();       // Wed Apr 08 2015 10:42:25 GMT+0800 (CST)

如果不传参数则自动返回当前日期格式,传参必须传入表示日期的毫秒数,提供两种方法:Date.parse()Date.UTC()

Date parse()

传入的必须是字符串,目前可以支持的格式有四种:

  • “月/日/年”,如:4/8/2015
  • “英文月名 日,年”,如:April 8,2015
  • “英文星期几 英文月名 日 年 时:分:秒 时区”,如:Wed Apr 08 2015 10:42:25 GMT+0800 (CST)
  • “YYYY-MM-DDTHH:mm:ss.sssZ”,如:2015-04-08T00:00:00,也可以2015-04等,只有EC5以上才支持。

当传入的字符串不是以上标准格式时即返回NaN,所以创建时传参可以是:

var now = new Date(Date.parse("2015-04-08"));       // Wed Apr 08 2015 08:00:00 GMT+0800 (CST)
//但实际上不显示的调用 Date.parse,直接传入一个字符串,Date也会在后台调用Date.parse(),所以上面的方法等价于:
var now = new Date("2015-04-08");                   // Wed Apr 08 2015 08:00:00 GMT+0800 (CST)

Date.UTC()

返回的同样也似乎毫秒数。但是这里传入的月份是从0(0即一月)开始计数的,年月不能省略,日期省略默认为1,其他省略,默认为0;

  • “月/日/年”,如:2015, 3, 8, 10, 55, 55
var now = new Date(Date.UTC(2015, 3, 8, 10, 55, 55))    // Wed Apr 08 2015 18:55:55 GMT+0800 (CST)
var now = new Date(2015, 3, 8, 10, 55, 55)              // Wed Apr 08 2015 10:55:55 GMT+0800 (CST)

上面两种方法看似能得出相同的值,但是他们是不同的,第一种日期是基于GMT来创建的,第二种是根据本地时区来创建的,所以是会有区别的。

日期格式化方法

基本的转化方法为toString()toLocaleString(),在日期对象里这两个方法被重写。且执行效果各个浏览器表现不一致。 一下为chrome的表现。

var now = new Date();

// toString():以特定于实现的格式显示详细日期;
now.toString();             // Wed Apr 08 2015 13:50:35 GMT+0800 (CST)

// toLocaleString():以特定地区的格式显示详细时间;
now.toLocaleString();       // 2015/4/8 下午1:50:35

// toDateString():以特定于实现的格式显示星期几、月、日和年;
now.toDateString();         // Wed Apr 08 2015

// toTimeString():以特定于实现的格式显示时、分、秒和时区;
now.toTimeString();         // 13:50:35 GMT+0800 (CST)

// toLocaleDateString():以特定地区的格式显示星期几、月、日和年;
now.toLocaleDateString();   // 2015/4/8(以本地时间格式为准)

// toLocaleTimeString():以特定地区的格式显示时、分、秒和时区;
now.toLocaleTimeString();   // 下午1:50:35(以本地时间格式为准)

// toUTCString():以特定于实现的格式完整的UTC日期;
now.toUTCString();          // Wed, 08 Apr 2015 05:50:35 GMT

转为时间戳的基本方式有valueOf()。时间戳可以用于比较大小,相减。当然如果直接对日期对象进行比较大小和运算时, 后台会自动调用valueOf()方法。运算结果也是时间戳。如:(环境为chrome)

var now = new Date();
    time1 = new Date("2015-04-08"),
    time2 = new Date("2015-04-07");

time1 > time2;      // true
time1 - time2;      // 86400000( 1000 * 60 * 60 * 24 )

now.valueOf();      // 1428473242845
now.getTime();      // 1428473242845
+now;               // 1428473242845
Date.now();         // 1428473242845(IE9+)

常用时间对象API

getTime();              // 与 valueOf 相同
setTIme(时间戳);         // 以毫秒为单位设置时间
getFullYear();          // 获取四位数的年份
setFullYear(yyyy);      // 设置四位数的年份
getMonth();             // 获取月份,以0开始计数
setMonth(mm);           // 设置月份,以0开始计数
getDate();              // 获取天数
setDate(DD);            // 设置天数
getDay();               // 获取星期几,0为周日
setDay(D);              // 设置星期几
getHours();             // 获取小时数(0-23)
setHours(HH);           // 设置小时数(0-23)
getMinutes();           // 获取分钟数(0-59)
setMinutes(MM);         // 设置分钟数(0-59)
getSeconds();           // 获取秒数(0-59)
setSeconds(SS);         // 设置秒数(0-59)
getMilliseconds();      // 获取毫秒数(0-999)
setMilliseconds(毫秒数); // 设置毫秒数(0-999)

以上方法除了time都有一个UTC格式方法,如getUTCFullYear,这个是UTC日期中的四位数年份。


Function对象

EC中没有函数重载的概念。主要看例子来说明,第一个例子我们来看函数声明式,解析器会率先读取函数声明, 并使其在执行任何代码之前可用,

console.log(sum(10,10));        // 10
function sum(num1, num2){
    return num1 + num2;
}

函数表达式,这种方式则必须等到解析器执行到它所在的代码行才会被解释执行。当然为什么第一个会是undefined呢?因为var sum1声明被提前了。 例子如下:

console.log(sum1,sum1(10,10));      // undefined,undefined is not a function
var sum1 = function(num1, num2){
    return num1 + num2;
}

函数是对象,函数名是指针。一个对象可以有多个名字,这些名字之间相互不影响

function sum(num1, num2){
    return num1 + num2;
}
console.log(sum(10, 10));

var anotherSum = sum;
sum = null;
console.log(anotherSum(10, 20));

函数的属性:argumentsthiscallee

callee:是一个指针,指向拥有这个arguments对象的函数。Opera的EC3不支持。 EC5还假如了caller属性。严格模式下这两个属性都会报错。使用请看例子

function allOuter(){
    outer();
}

function outer(){
    inner();
}

function inner(){
    console.log(arguments.callee);                   //inner
    console.log(arguments.callee.caller);            //outer
    console.log(arguments.callee.caller.caller);     //allOuter
}

allOuter();

this:引用的是函数据以执行的环境对象,即调用者。

length:是指期望接受参数长度。

apply()和call():主要改变this指针,两种方法只是在接受参数上又差异。

window.color = "red";
var o = {color: "blue"};

function sayColor(name){
    console.log(name + "`s color is " + this.color);
}

sayColor.apply(window,['window']);          // window`s color is red
sayColor.call(o,'o');                       // o`s color is blue

bind:在函数的生存周期里永久指定thiscallapply都无法改变。

var oSayColor = sayColor.bind(o);
oSayColor('new');                           // new`s color is blue
oSayColor.apply(window,['window']);         // window`s color is blue

Number类型

声明有字面量和构造器两种:

var numberObject = new Number(10),
    numberValue = 10;
console.log(typeof numberObject);               // "object"
console.log(typeof numberValue);                // "number"
console.log(numberObject instanceof Number);    // true
console.log(numberValue instanceof Number);     // false

转为字符串的方法有toString(进制数)或者+ ''

var num = 10;
console.log(num.toString());            // 10
console.log(num.toString(2));           // 1010
console.log(num + '');                  // 10

取小数点后几位进行舍入(四舍五入)各个浏览器舍入的标准,和保留位数的限制都不一样。标准是20位。

var num = 10.005;
console.log(num.toFixed(2));            // 10.01
console.log(num.toExponential(2));      // 1.00e+1
console.log(num.toPrecision(2));        // 10   自动识别是按照以上哪种形式表达,但取的位数是总位数

String类型

声明方式和Number一样,主要记一下String的API。

取字符串某个字符:

var stringValue = "hello world";
console.log(stringValue.charAt(1));         // 'e'
console.log(stringValue.charCodeAt(1));     // 101
console.log(stringValue[1]);                // 'e'

拼接字符串:

var stringValue = "hello";
console.log(stringValue.concat(" world","!"));      // 'hello world!'
console.log(stringValue + " world" + "!");          // 'hello world!'

截取字符串:

var stringValue = "hello world";
console.log(stringValue.slice(3));              // lo world
console.log(stringValue.substring(3));          // lo world
console.log(stringValue.substr(3));             // lo world

// 一看好像都是一样的,区别在哪里呢?

console.log(stringValue.slice(-3));             // rld
console.log(stringValue.substring(-3));         // hello world
console.log(stringValue.substr(-3));            // rld

// slice 和 substr 进行了换算11 + (-3) = 8,取的是slice(8),substr(8),但substring(0)

// slice 和 substr 还有区别
console.log(stringValue.slice(3,-4));           // lo w
console.log(stringValue.substring(3,-4));       // hel
console.log(stringValue.substr(3,-4));          // ""

// slice 取的是(3,11 +(-4))= (3,7);
// substring取的是(3,0);但substring会让小的数字在前面,最终取的是(0,3)
// substr取的是(3,0),为空

获取字符串位置:

var stringValue = "hello world";
console.log(stringValue.indexOf("o"));          // 4
console.log(stringValue.lastIndexOf("o"));      // 7

//可以接受参数,表示起始位置
console.log(stringValue.indexOf("o",6));        // 7
console.log(stringValue.lastIndexOf("o",6));    // 4

去掉字符串前后的空格,中间的空格不会去掉

var stringValue = "   hello world    ";
console.log(stringValue.trim());                // hello world

大小写转换

var stringValue = "hello world";
console.log(stringValue.toLocaleUpperCase());   // HELLO WORLD
console.log(stringValue.toUpperCase());         // HELLO WORLD
console.log(stringValue.toLocaleLowerCase());   // hello world
console.log(stringValue.toLowerCase());         // hello world

将字符串基于某种分隔符分割成多个字符串并用数组保存起来

var colorText = "red,blue,green,yellow";
console.log(colorText.split(","));              // ["red", "blue", "green", "yellow"]

字符串比较:

var stringValue = "yellow";
console.log(stringValue.localeCompare("brick"));    // 1
console.log(stringValue.localeCompare("yellow"));   // 0
console.log(stringValue.localeCompare("zoo"));      // -1

字符串直接生成HTML标签,这类东西有很多的。

var name = "karyn";
name.anchor("song");        // '<a name="song">karyn</a>'
name.big();                 // '<big>karyn</big>'
...

Global

encodeURIComponentdecodeURIComponent

var url = "https://www.baidu.com/",
    _url = encodeURIComponent(url);         // 'https%3A%2F%2Fwww.baidu.com%2F'
decodeURIComponent(_url);                   // 'https://www.baidu.com/'

Math

Math.max(1,2,3,4,5,6,7);            // 7

// 以下方法等价于上面的写法,同样数组还可以用sort
var value = [1,2,3,4,5,6,7];
Math.max.apply(Math,value);         // 7

Math.ceil(25.9);                    // 26  向上取整
Math.floor(25.9);                   // 25  向下取整
Math.round(25.9);                   // 26  四舍五入

Math.random();                      // 取 0-1之间的随机数
// 怎么取一个范围的数呢?可以通过公式
Math.floor(Math.random() * 可能值的总数 + 第一个可能的值);
// 如:2-10
Math.floor(Math.random() * 9 + 2);