后盾人:JS第三章-数据类型

字符串截取方法

 1 let hd = 'abcdefg'
 2 
 3 hd.slice(1)    //bcdefg
 4 hd.substring(1)    //bcdefg
 5 hd.substr(1)    //bcdefg
 6 
 7 
 8 hd.slice(1,3)    //bc
 9 hd.substring(1,3)    //bc
10 hd.substr(1,3)    //bcd
11 
12 
13 hd.slice(-2)    //fg
14 hd.substring(-2)    //abcdefg(负数没有意义,相当于0)
15 hd.substr(-2)    //fg
16 
17 hd.slice(-3,-1)    //ef
18 hd.substring(-2)    //abcdefg(负数没有意义,相当于0)
19 hd.substr(-3,-1)    //ef

字符串检索

 1 let hd = ‘abcdefg’
 2 
 3 hd.indexOf('a') // 0
 4 hd.indexOf('z') // -1 (没有返回-1)
 5 
 6 hd.lastIndexOf('a') // 0 右边开始查找 返回下标
 7 
 8 hd.startsWith(‘a’)//true  (检索开始第一字符,区分大小写)
 9 hd.endsWith(‘g’)//true  (检索结束最后一位字符,区分大小写)
10 
11 hd.includes('a')    //true
12 hd.includes('a',10)    //false (在第10位开始查找)

字符串替换

let hd = 'abcdefg'

hd.replace('a', 'zz')   //zzbcdefg

字符串函数

repeat(3)  重复处理3次

字符串和其他类型之间的转换

let hd = “99.9abcd”

数字

parseInt(hd)  // 99   数字类型

parseFloat(hd) // 99.9 

字符串转数组

hd.split(‘ ’)  // [9,9,.,9,a.....]

数组转字符串

arry = [aa,bb,cc]

arrt.join('|')  // aa|bb|cc 

Boolean 类型转换

数字和字符串、日期、对象等都可以使用 ‘!!’双感叹号。或者Boolean()

 数字类型

 isNntager()  //判断是否为整数,返回布尔值

toFixed(2)  //保留2位小数

Number.isNaN()  //返回布尔值

parseInter()  //取整数

parseFloat(2)  //取两位小数

Number([])  // 空数组为0;一个值返回对应值;多个值返回NaN

Number({})  //对象一般返回NaN

数学计算方法 Math

Math.min(1,2,3,)  //1

Math.max(1,2,3,)  //3

Math.ceil(5.01)  //6;向上取整

Math.floor(5.99)  //5;向下取整

Math.round(5.56)  //6;四舍五入取整数

Math.random()  //随机数  <=0~1<之间

Math.floor(Math.random()*5+1)  //0~5之间的随机整数(包括 5)

//随机数组

function arrayRandomValue(array, start=1, end){
    end = end ? end : array.length;
    start--;
    const index = start + Math.floor(Math.random()*(end - start))
    return array[index]
}

日期  new Date()

new Date()  //对象类型, *1的时候可以得到时间戳

Date()  //字符串类型

Date.now()  //获取时间戳

time()   //时间标志位开始

timeEnd() //时间标志位结束

new Date(1993,11,14,12,00,00)  //也可以得到时间。是数组的话,用...展开语法

转换时间戳

let date =  new Date()  //下面四种方法都可以

date*1

Number(date)

date.valueOf()

date.getTime()

getFullYear()  //年

getMonth()+1  //月

getDate()  //日

getHours()  //时

getMinutes()  //分

getSeconds()  //秒

//获取不同的时间格式
function dateFormat(date, format = "YYYY-MM-DD HH:mm:ss") {
    const config = {
    YYYY:date.getFullYear(),
    MM.getMonth(),
    DD:date.getdate(),
    HH:date.getHours(),
    mm:date.getMinutes(),
    ss:date.getSeconds(),
};
for(const key in config){
    format = format.replace(key, config[key]);
}
return format;
}

时间库推荐 Moment.js

原文地址:https://www.cnblogs.com/jidanbufan/p/14277626.html