1.输入一个值,返回其数据类型
function varType(obj) {
const toString = Object.prototype.toString
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
}
return map[toString.call(obj)]
}
varType('foo') //string
varType(123) //number
2.根据身份证获取性别
function getSexById(userCard) {
if (parseInt(userCard.substr(16, 1), 10) % 2 === 1) {
// 男
return '0'
} else {
// 女
return '1'
}
}
3.返回当前的时间(年月日时分秒)
function getDateTime() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() + 1,
minute = date.getMinutes(),
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
4.获得滚动条的滚动距离
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset
}
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop
}
}
}
5.获得视口的尺寸
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
6.数组去重
1.扩展运算符
const arr = [1,2,2,4,null,null,'3','abc',3,5,4,1,2,2,4,undefined,null,null,'3','abc',3,5,4]
const newArr=[...new Set(arr)]
console.log(newArr); //[1,2,4,null,'3','abc',3,5,undefined]
2.Array.from
console.log(newArr); //[1,2,4,null,'3','abc',3,5,undefined]
7.检查数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);//true
\