JavaScript
常用方法
在前端开发过程中,很容易出现一些常用的或者常见的方法,下面是一些常用的 JavaScript
方法:
生成随机颜色
javascript
function randomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
console.log(randomColor()); // #E94221
生成随机指定长度的字符串
javascript
function randomString(length) {
var result = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(randomString(10)); // "kL7y3b2v9z"
获取指定格式的日期、时间字符串
Javascript
/**
* @author Yh
* @description 日期类
* @date 2024-10-14
* @version 1.0.0
*/
// 获取当前日期是星期几
function getWeek(date) {
const day = date.getDay();
const arr = ["日", "一", "二", "三", "四", "五", "六"];
return "星期" + arr[day];
}
console.log(getWeek(new Date())); // 星期一
// 转换日期格式
function formatDate(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
}
console.log(formatDate(new Date())); // 2024-10-14
// 转换时间格式
function formatTime(date) {
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const h = hour < 10 ? '0' + hour : hour;
const min = minute < 10 ? '0' + minute : minute;
const s = second < 10 ? '0' + second : second;
return `${h}:${min}:${s}`;
}
console.log(formatTime(new Date())); // 10:10:10
// 转换日期时间格式
function formatDateTime(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();
const m = month < 10 ? '0' + month : month;
const d = day < 10 ? '0' + day : day;
const h = hour < 10 ? '0' + hour : hour;
const min = minute < 10 ? '0' + minute : minute;
const s = second < 10 ? '0' + second : second;
return `${year}-${m}-${d} ${h}:${min}:${s}`;
}
console.log(formatDateTime(new Date())); // 2024-10-14 10:10:10
对象合并
javascript
function mergeObject(obj1, obj2) {
let obj = {};
obj = { ...obj1, ...obj2 };
return obj;
}
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = mergeObject(obj1, obj2);
console.log(obj3); // {a: 1, b: 2, c: 3, d: 4}
数组去重
javascript
function unique(arr) {
return Array.from(new Set(arr));
}
const arr = [1, 2, 3, 2, 1, 4, 5, 4];
const newArr = unique(arr);
console.log(newArr); // [1, 2, 3, 4, 5]