js常用方法

/**
 * 获取文件后缀名
 * @param {String} filename
 */
 export function getExt(filename) {
    if (typeof filename == 'string') {
        return filename
            .split('.')
            .pop()
            .toLowerCase()
    } else {
        throw new Error('filename must be a string type')
    }
}
getExt("1.mp4") //->mp4


/**
 * 复制内容到剪贴板
 */
export function copyToBoard(value) {
    const element = document.createElement('textarea')
    document.body.appendChild(element)
    element.value = value
    element.select()
    if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(element)
        return true
    }
    document.body.removeChild(element)
    return false
}
//如果复制成功返回true
copyToBoard('lalallala')


/**
 * 休眠xxxms
 * @param {Number} milliseconds
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}
//使用方式
const fetchData=async()=>{
 await sleep(1000)
}


/**
 * 生成随机id
 * @param {*} length
 * @param {*} chars
 */
export function uuid(length, chars) {
    chars =
        chars ||
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    length = length || 8
    var result = ''
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)]
    return result
}
//第一个参数指定位数,第二个字符串指定字符,都是可选参数,如果都不传,默认生成8位
uuid()  


/**
 *深拷贝
 * @export
 * @param {*} obj
 * @returns
 */
export function deepCopy(obj) {
    if (typeof obj != 'object') {
        return obj
    }
    if (obj == null) {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}
const person={name:'xiaoming',child:{name:'Jack'}}
deepCopy(person) //new person


/**
 * 数组去重
 * @param {*} arr
 */
export function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
        throw new Error('The first parameter must be an array')
    }
    if (arr.length == 1) {
        return arr
    }
    return [...new Set(arr)]
}
uniqueArray([1,1,1,1,1])//[1]


/**
 * 对象转化为formdata
 * @param {Object} object
 */
 export function getFormData(object) {
    const formData = new FormData()
    Object.keys(object).forEach(key => {
        const value = object[key]
        if (Array.isArray(value)) {
            value.forEach((subValue, i) =>
                formData.append(key + `[${i}]`, subValue)
            )
        } else {
            formData.append(key, object[key])
        }
    })
    return formData
}
let req={
    file:xxx,
    userId:1,
    phone:'15198763636',
    //...
}
fetch(getFormData(req))


// 保留小数点以后几位,默认2位
export function cutNumber(number, no = 2) {
    if (typeof number != 'number') {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}


const empty = input => {
  return (typeof input == 'undefined' || !input || /^\s*(null|0|undefined|false|no)\s*$/i.test(input) || (input instanceof Array && !input.length) || (typeof input == 'object' && ((!Object.keys(input).length) || (('length' in input) && !input.length))));
}


/**
 * 防抖
 * @param {*} func 要进行debouce的函数
 * @param {*} wait 等待时间,默认500ms
 * @param {*} immediate 是否立即执行
 */
export function debounce(func, wait=500, immediate=false) {
    var timeout
    return function() {
        var context = this
        var args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                func.apply(context, args)
            }, wait)
        }
    }
}


/**
 * 节流,多次触发,间隔时间段执行
 * @param {Function} func
 * @param {Int} wait
 * @param {Object} options
 */
export function throttle(func, wait=500, options) {
    //container.onmousemove = throttle(getUserAction, 1000);
    var timeout, context, args
    var previous = 0
    if (!options) options = {leading:false,trailing:true}

    var later = function() {
        previous = options.leading === false ? 0 : new Date().getTime()
        timeout = null
        func.apply(context, args)
        if (!timeout) context = args = null
    }

    var throttled = function() {
        var now = new Date().getTime()
        if (!previous && options.leading === false) previous = now
        var remaining = wait - (now - previous)
        context = this
        args = arguments
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout)
                timeout = null
            }
            previous = now
            func.apply(context, args)
            if (!timeout) context = args = null
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining)
        }
    }
    return throttled
}
第三个参数options:
leading,函数在每个等待时延的开始被调用,默认值为false
trailing,函数在每个等待时延的结束被调用,默认值是true
可以根据不同的值来设置不同的效果:
leading-false,trailing-true:默认情况,即在延时结束后才会调用函数
leading-true,trailing-true:在延时开始时就调用,延时结束后也会调用
leading-true, trailing-false:只在延时开始时调用
function FormatDate(strTime, style) {
  if (!strTime) return "";
  var date = new Date(strTime);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  var weekday = date.getDay();
  var week_day = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  var week_dayN = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  if (hour < 10) {
    hour = "0" + hour;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }
  if (style == 'weekN') { //返回星期格式
    return month + "月" + day + "日 " + week_dayN[weekday];
  } else if (style == 'week') { //返回星期格式
    return month + "月" + day + "日 " + week_day[weekday];
  } else if (style == 'simple') {
    return year + "-" + month + "-" + day;
  } else if (style == 'minutes') {
    return year + "-" + month + "-" + day + " " + hour + ":" + minutes;
  } else if (style == 'month') {
    return month + "-" + day + " " + hour + ":" + minutes;
  } else if (style == 'day') {
    return year + "-" + month + "-" + day;
  } else {
    return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
  }
}


const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  // return [year, month, day].map(formatNumber).join('-')
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


function dateFormat(date, format) {
  if (!date)
    return '';
  format = format || 'Y-m-d';
  let _date = new Date(date);
  let [year, month, day, weekDay, hours, minutes, seconds] = [_date.getFullYear() + '', (_date.getMonth() + 1) + '', _date.getDate() + '', _date.getDay() + '', _date.getHours() + '', _date.getMinutes() + '', _date.getSeconds() + '']
  let [monthEn, weekEn] = [_date.toUTCString().substr(8, 3), _date.toUTCString().substr(0, 3)];
  let weekDay_ISO8601 = (weekDay === '0') ? '7' : weekDay;
  return format.replace(/Y/g, year) //1970
    .replace(/y/g, year.slice(-2)) //70
    .replace(/m/g, ('0' + month).slice(-2)) //09
    .replace(/n/g, month) //9
    .replace(/M/g, monthEn) //Sep
    .replace(/F/g, months[monthEn].en) //September
    .replace(/\_F/g, months[monthEn].cn) //九
    .replace(/j/g, day) //9
    .replace(/d/g, ('0' + day).slice(-2)) //09
    .replace(/D/g, weekEn) //Sun
    .replace(/_l/g, weeks[weekEn].cn) //日
    .replace(/l/g, weeks[weekEn].en) //Sunday
    .replace(/w/g, weekDay) //0
    .replace(/N/g, weekDay_ISO8601) //7
    .replace(/H/g, ('0' + hours).slice(-2)) //06
    .replace(/G/g, hours) //6
    .replace(/i/g, ('0' + minutes).slice(-2)) //06
    .replace(/s/g, ('0' + seconds).slice(-2)); //06
}
//从数组中删除重复项
const numbers = [1, 1, 10, 5, 3, 3, 2, 2];
const uniqueNumbers = [...new Set(numbers)]; // -> [1, 10, 5, 3, 2]

//单行 If-Else 语句
ageGroup = age > 18 ? "An adult" : "A child";

//较短的 If-Else 的空合并
if(maybeSomething){
  console.log(maybeSomething)
} else {
  console.log("Nothing found")
}
console.log(maybeSomething ?? "Nothing found")

//防止崩溃的可选链
const student = {
  name: "Matt",
  age: 27,
  address: {
    state: "New York"
  },
};
console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined
console.log(student?.address?.ZIPCode); // Doesn't exist - Returns undefined

//交互变量
let x = 1,y = 2;
[x, y] = [y, x];

//将任何值转换为布尔值
!!true    // true

//扩展运算符
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
let newArray = nums1.concat(nums2);
newArray = [...nums1, ...nums2];

//传播解构
const student = {
  name: "Matt",
  age: 23,
  city: "Helsinki",
  state: "Finland",
};
const name = student.name;
const age = student.age;
const address = { city: student.city, state: student.state };
const { name, age, ...address } = student;

//使用 && 进行短路评估
var isReady = true;
isReady && doSomething();

//模板字符串
const age = 41;
const sentence = `I'm ${age} years old`;

//从数组中查找特定元素
const fruits = [
  { type: "Banana", color: "Yellow" },
  { type: "Apple", color: "Green" }
];
yellowFruit = fruits.find((fruit) => fruit.color === "Yellow");

//对象属性赋值
const name = "Luis", city = "Paris", age = 43, favoriteFood = "Spaghetti";
const person = { name, city, age, favoriteFood };

//forEach()
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));

//默认功能参数
function pickUp(fruit = "Banana") {
  console.log(`I picked up a ${fruit}`)
}
pickUp("Mango"); // -> I picked up a Mango
pickUp();        // -> I picked up a Banana

//将对象的值收集到数组中
const info = { name: "Matt", country: "Finland", age: 35 };
const data = Object.values(info);

//检查一个项目是否存在于数组中
let numbers = [1, 2, 3];
const hasNumber1 = numbers.includes(1)     // -> True

//压缩多个条件
const num = 1;
if([1,2,3].includes(num)){
  console.log("Yay");
}

//指数运算符
Math.pow(4,2); // 16
4**2 // 16

// Math.floor() 简写
Math.floor(5.25) // -> 5.0
~~-12.25 // -> -12
~~5.25 // -> 5.0
//~~大于0的时候可以正常作为Math.floor使用,小于0的时候是作为Math.ceil使用的

//用一行代码分配多个值
let num1, num2;
[num1, num2] = [10, 100];//num1 = 10;num2 = 100;

student = {
  name: "Matt",
  age: 29,
};
let { name, age } = student;//let name = student.name;let age = student.age;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值