js面试,其他基础相关问题

一、日期相关问题
1.1
js中内置了一个Date对象

Date.now()//获取当前时间毫秒数,13位数

let dt = new Date()
dt.getTime()//获取毫秒数
dt.getFullYear()//获取年
dt.getMonth()//0-11
dt.getDay(); //星期0-6
dt.getDate()
dt.getHours()//0-23
dt.getMinutes()//0-59
dt.getSeconds()//秒(0-59)
1.2
工作当中会经常用到时间戳,我曾经就遇到一个小白问我时间戳是什么…(我当时也是小白不过还是略懂)
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
那么以下代码就是js获取当前日期的时间戳,均为数字类型

let timestamp1 = Date.parse(new Date());//精确到秒
let timestamp2 = (new Date()).valueOf();//精确到毫秒
let timestamp3 = new Date().getTime();//精确到毫秒
let timestamp4 =Date.now(); //精确到毫秒
console.log(timestamp1,timestamp2,timestamp3,timestamp4)
1.3
时间戳转日期格式

function DateFormat(value){
let numvalue = Number(value),dt=null;
if(String(numvalue).length===13){
dt = new Date(numvalue)
}else if(String(numvalue).length === 10){
dt = new Date(numvalue*1000)
}
let year = dt.getFullYear();//年
let month = dt.getMonth();//月
if(month<10){
month = 0${month}
}
let date = dt.getDate()+1//日期
if(date<10){
date = 0${date}
}
let houer = dt.getHours()//小时
if(houer<10){
houer = 0${houer}
}
let minu = dt.getMinutes()//分钟
if(minu<10){
minu = 0${minu}
}
let seconds =dt.getSeconds()//秒
if(seconds<10){
seconds = 0${seconds}
}
let result = ${year}/${month}/${date} ${houer}:${minu}:${seconds}
return result
}
let a = DateFormat(1541080568437)
console.log(a)
这是 我自己学Date之后写的一个时间戳转换,比较脑残,但是作为学习还是能看的
然后就是若想用这个函数来处理vue里的时间戳;那么把这个函数扩展到vue的实例原型上即可

Vue.prototype.DateFormat = DateFormat
//然后就能在vue里用这个方法,而且还能在vue的插值语法中使用{{DateFormat(待处理数据)}}
二、
数组API
2.1 forEach
遍历所以的数组元素

let arr = [1,3,5]
arr.forEach(function(item,index){
console.log(item,index)
})
//item为值,index为索引
2.2 every
判断数组元素是否都满足一个条件

let arr = [1,3,5]
let result = arr.every((item,index)=>{
//条件添加,意思就是数组的每一个元素都小于4则输出true
if(item<4){
return true
}
})
console.log(result)//false
2.3 some
用来判断所有的数组元素,只要有一个满足条件即可

let arr = [1,3,5]
let result = arr.some((item,index)=>{
//条件添加
if(item<4){
return true
}
})
console.log(result)//true
2.4 sort 排序

let arr = [1,6,2,5,7,3,6,4,5]
let arrx = arr.sort((a,b)=>{
return a-b//从小到大
})
console.log(arrx)
console.log(arr)
let arro = arr.sort((a,b)=>{
return b-a//从大到小
})
console.log(arro)
console.log(arr)
其实这个数组api是改变了原数组了的
2.5 map
将数组重新组装并返回

let arr = [1,5,3,4,6]
let arrx = arr.map((item,index)=>{
return item+index;
})
console.log(arr)
console.log(arrx)
这个数组api没有改变原数组

2.6 filter
过滤掉不符合条件的元素

let arr = [1,5,3,4,6]
let arrx = arr.filter((item,index)=>{
if(item>3){
return true
}
})
console.log(arr)
console.log(arrx)//[5, 4, 6]
三、对象API
for…in…

let obj = {
x:100,
y:200,
z:300
}
for(let key in obj){
if(obj.hasOwnPropery(key)){
console.log(key,obj[key])
}
}
// x 100 y 200 z 300

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章