前端 JavaScript
练习案例以及常用案例
实现 99 乘法表
在 node
环境中运行
process.stdout.write()
node
环境中不换行输出
function multiplication() {}
let txt = "";
for (let i = 1; i <= 9; i++) {
txt = i > 4 ? "" : " ";
for (let j = 1; j <= i; j++) {
txt = i + "*" + j + "=" + i * j;
txt = txt + " ";
process.stdout.write(txt); // node 不换行输出
}
console.log(""); // 实现换行
}
生成随机字段
采用 Class
类封装 生成 特定长度的随机字段
前端生成 用于一次性用户身份识别
class Tools {
constructor() {
this.all_str =
"abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
}
// n: 定义字符长度
generateMixed(n) {
let str = "";
let arr = this.all_str.split("");
for (let i = 0; i < n; i++) {
str += arr[Math.floor(Math.random() * this.all_str.length)];
}
return str;
}
}
let str = new Tools();
console.log(str.generateMixed(32));
export { Tools }; // 暴露封装函数
获取 Date
时间的各种类型
//
class DateFunc {
constructor() {
(this.date = new Date()),
(this.date_now = Date.now()),
(this.get_full_year = this.date.getFullYear()),
(this.get_year = this.date.getYear()),
(this.get_month = this.date.getMonth()),
(this.get_date = this.date.getDate()),
(this.get_day = this.date.getDay()),
(this.get_timer = this.date.getTime()),
(this.get_hour = this.date.getHours()),
(this.get_minute = this.date.getMinutes()),
(this.get_second = this.date.getSeconds()),
(this.get_milliseconds = this.date.getMilliseconds());
}
Timer() {
// 2023-03-01T03:13:55.881Z
return this.date;
}
Timestamp() {
// 时间戳
return this.date_now;
}
LocalString() {
// 2023/3/1 11:13:55
return this.date.toLocaleString();
}
Dates() {
// 2023-3-1
return this.get_full_year + `-${this.get_month + 1}-${this.get_date}`;
}
Date2() {
// 2023.3.1
return this.Dates().replaceAll("-", ".");
}
DateString() {
// Wed Mar 01 2023
return this.date.toDateString();
}
ISOString() {
// 2023-03-01T03:25:11.535Z
return this.date.toISOString();
}
Json() {
// 2023-03-01T03:25:11.535Z
return this.date.toJSON();
}
LocalDateString() {
// 2023/3/1
return this.date.toLocaleDateString();
}
LocalTimeString() {
// 11:27:42 GMT+0800 (中国标准时间)
return this.date.toTimeString();
}
String() {
// Wed Mar 01 2023 11:31:56 GMT+0800 (中国标准时间)
return this.date.toString();
}
TimeString() {
// 11:31:56 GMT+0800 (中国标准时间)
return this.date.toTimeString();
}
UTCString() {
// Wed, 01 Mar 2023 03:31:56 GMT
return this.date.toUTCString();
}
}
export { DateFunc };
常用输入框验证
class Rules {
constructor() {
this.num_reg = /^[1][3-9][0-9]{9}$/;
this.mail_check = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
}
username(value) { // 用户名不能为空
return value ? true : false;
}
email(value) { // 邮箱验证
return !this.mail_check.test(value) ? false : true;
}
phone(value){ // 手机号验证
return !this.num_reg.test(value) ? false : true;
}
password(value) { // 密码不能为空并且密码长度不能小于6
let res1 = value ? true : false;
let res2 = value.length < 6 ? false : true;
return res1 && res2
}
twicepwd(repwd, pwd){ // 二次确认密码验证
return repwd != pwd ? false : true;
}
repwd(repwd, pwd){ // 重置密码验证
return repwd == pwd ? false : true;
}
}
export { Rules };