js基础语法.md 7.1 KB

《前端科普系列-Web:一路前行一路忘川》

《前端科普系列-Node.js:换个角度看世界》

《前端科普系列-CommonJS:不是前端却革命了前端》

《前端科普系列-Babel:把 ES6 送上天的通天塔》

《前端科普系列-ESlint:守住优雅的护城河》

六种数据类型

JavaScript 有六种数据类型:

  • 数值
  • 字符串
  • 布尔值
  • null
  • undefined
  • 对象 其中,数值、字符串、布尔值是原始类型,不能再细分了。对象则是合成类型,由多个原始类型的值合成,可以看作是存放各种值的容器。null 和 undefined 一般是看作两个特殊值。

通过以下三种方式可以确定值的类型:

  • typeof
  • instanceof
  • Object.prototype.toString 方法
// 数值
var a = 123;
console.log(typeof a); //number
// 字符串
var b = '123';
console.log(typeof b); //string
//布尔
var c = true;
console.log(typeof c); //boolean
//undefined
var d;
console.log(typeof d); //undefined
//函数
var f = function() {console.log('f');}
console.log(typeof f); //function

字符串转为数值

JavaScript内部所有的数值都是以64位浮点数形式存储的,即使整数也是如此。所以 1 和 1.0 是相同的,是同一个数。

console.log(1 === 1.0); // true

由于浮点数不是精确的值,所以涉及小数的比较和运算要特别小心!

var a = 0.1, b = 0.2, c = 0.3;
console.log(a+b); // 0.30000000000000004
console.log(a+b === c); // false

console.log(0.3/0.1); // 2.9999999999999996
console.log(0.3-0.2); // 0.09999999999999998
console.log(0.2-0.1); // 0.1
console.log(0.3-0.2 == 0.2-0.1); // false

## 转为布尔值

```js
var a = '';
if (a) {console.log('a:true');};
var b = ' ';
if (b) {console.log('b:true');};
var c = 0;
if (c) {console.log('c:true');};
var d = 'true';
if (d) {console.log('d:true');};
var e = 'false';
if (e) {console.log('e:true');};
var f = {};
if (f) {console.log('f:true');};
var g = null;
if (g) {console.log('g:true');};
var h;
if (h) {console.log('h:true');};

如果JavaScript认为某个位置应该是布尔值,会将该位置的值自动转为布尔值。转换规则是:除了以下6个值会被转成false,其他值都视为true。

  • undefined
  • null
  • false
  • 0
  • NaN
  • '' 或 "" (空字符串)

数组 Array

定义

let arr1 = ["周一", "周二", "周三"];
let arr2 = new Array("2019年", "2020年", "2021年");

属性

Array 具有 length 属性,即可获取也可设置。

// 获取数据长度
var arrayLength = arr.length;
// 设置数组长度(超出数组长度的元素将被抛弃)
arr.length = 2;

方法

pop(); // 取出并删除数组最后一个元素

push(element); // 在数组末尾追加元素

shifit(); // 取出并删除数组第一个元素

unshift(element); // 在数组开头添加元素

indexOf(element); // 查找元素的第一个位置

lastIndexOf(element); // 查找元素的最后一个位置

splice(start, length, [e1, ...]); // 从start位置开始删除length个元素,并插入后面的参数元素(相当于替换)

var arr1 = [2, 4, 6];
arr1.splice(1, 2, 1, 3, 5);
console.log(arr1);	// 输出 '[2, 1, 3, 5]'
join(char); // 数组元素以字符相连接,并返回字符串

sort([fn]); // 默认把元素看做字符串自然排序,也可传入函数自定义排序

var arr2 = [3, 5, 2, 9];
arr2.sort(function(n1, n2) {
	return n1 - n2;	// 前者大于后者,升序排列
});
console.log(arr2);	// 输出 '[2, 3, 5, 9]'
遍历
var arr = ['冰箱', '电视', '手机'];
// 第1种遍历
for (var i=0; i<arr.length; i++) {
    console.log(i, arr[i]);
}

// 第2种遍历
arr.forEach(function(item, index, array){
    console.log(index, item);
})

对象 Object

函数 function

一个函数应该只返回一种类型的值。

函数中有一个默认的数组变量arguments,存储着传入函数的所有参数。为了使用函数参数方便,建议给参数起个名字。

function fun1(obj, name, value){
    console.log(arguments);
    console.log(obj);
    console.log(name);
    console.log(value);
}
fun1({'id':12}, 'username', '张三');

日期 Date

定义

var date1 = new Date();
var date2 = new Date(timestamp);	// timestamp 毫秒单位的时间戳
var date3 = new Date(year, month-1, dayOfMonth, hour, minute, second);

方法

getFullYear();  //获取年份 getMonth();    //获取月份,月份从0开始,即0表示1月,1表示2月,以此类推 getDate();    //获取当前月份的第几日 getHours();   //时 getMinutes();  //分 getSeconds();  //秒 getTime(); // 毫米级时间戳

扩展

/**
 * 扩展Date对象的功能
 * @param format
 * @returns
 * @example  (new Date()).format('yyyy-MM-dd hh:mm:ss')    结果是 2018-08-13 08:42:34 这样的格式 ;
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

/**
 * 扩展Date对象的功能
 * 获取上一个月日期对象
 * @param date
 * @returns {Date}
 */
Date.prototype.getPreMonth = function() {
    var year = this.getFullYear();
    var month = this.getMonth()+1;
    var day = this.getDate();
    var hour = this.getHours();
    var minute = this.getMinutes();
    var second = this.getSeconds();
    
    var y = year;
    var m = parseInt(month) - 1;
    if (m == 0) {    // 如果是一月
        y = parseInt(y) - 1;
        m = 12;
    }
    
    var monthDays = new Date(y, m, 0).getDate(); //获取 m 月的天数
    var d = day;
    if (d > monthDays) {
        d = monthDays;
    }
    return new Date(y, m-1, d, hour, minute, second);
}


/**
 * 扩展Date对象的功能
 * 获取下一个月的日期
 * @param date
 * @returns {Date}
 */
Date.prototype.getNextMonth = function(){
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    
    var y = year;
    var m = parseInt(month) + 1;
    if (m == 13) {
        y = parseInt(y) + 1;
        m = 1;
    }
    
    var d = day;
    var monthDays = new Date(y, m, 0).getDate(); // 获取 m 月的天数
    if (d > monthDays) {
        d = monthDays;
    }
    return new Date(y, m-1, d, hour, minute, second);
}