字符串
repeat | 重复指定次数的字符串 | 'Apple'.repeat(3); >>> AppleAppleApple |
substr | 提取长度 | 'https://www.xxx.com/'.substr(0, 5); >>> https |
substring | 提取之间 | 'https://www.xxx.com/'.substring(1, 5); >>> ttps |
slice | 提取片段 | 'https://www.xxx.com/'.slice(0, 5); >>> https |
'https://www.xxx.com/'.slice(3); >>> ttps://www.xxx.com/ | ||
toUpperCase | 转换小写 | |
toLowerCase | 转换大写 | |
charCodeAt | 转换为Unicode编码 | 'a'.charCodeAt(); >>> 97 |
fromCharCode | 转换为ASCII编码 | String.fromCharCode('97'); >>> a |
indexOf | 查找第一个匹配值 | '123123'.indexOf('23'); >>> 1 |
lastIndexOf | 查找最后一个匹配值 | '123123'.lastIndexOf('23'); >>> 4 |
charAt | 返回指定位置的字符。 | 'Apple'.charAt(0); >>> 1 |
includes | 判断是否包含指定字符串或字符 | 'Apple'.includes('pp'); >>> true |
endsWith | 判断当前字符串是否是以指定的子字符串结尾的(区分大小写) | 'Apple'.endsWith('e'); >>> true |
startsWith | 判断当前字符串是否是以指定的子字符串开头的(区分大小写) | 'Apple'.startsWith('A'); >>> true |
数值
parseFloat | 转换为浮点型 |
parseInt | 转换为整型 |
toString | 以字符串返回数值 |
toExponential | 四舍五入并使用(指数)计数法的数字 |
toFixed | 保留小数点 |
toPrecision | 保留小数点 |
代码-转换进制
var num = 0;
num = 10; num.toString(2); // >>> 1010
num = parseInt(1010, 2); // >>> 10
num = 16; num.toString(8); // >>> 20
num = 100; num.toString(16); // >>> 64
代码-小数点保留
// 指定位数小数的数字
var x = 0;
x = 9.656;
x.toFixed(0); // >>> 10;
x.toFixed(2); // >>> 9.66;
x.toPrecision(); // >>> 9.656
x.toPrecision(4); // >>> 9.656
代码-游戏金币格式化
const formatMoney = (money) => { return money.toLocaleString(); };
console.log(formatMoney(123456789)); // >>> 123,456,789
数组
length | 获取或更改数组长度 | |
fill | 填充数组 | |
join | 分隔数组 | ['a','b','c'].join('-') >>> a-b-c |
concat | 合并数组 | |
slice | 切割数组 | |
isArray | 判断数组 | Array.isArray(array) |
includes | 包含某个元素 | [10,20,30].includes(20); >>> true |
indexOf | 搜索数组中的元素,并返回它所在的位置。 | [10, 20, 30].indexOf(20) >>> 1 |
lastIndexOf | 搜索数组中的元素,并返回它最后出现的位置。 | |
push | 添加末尾 | |
pop | 删除末尾 | |
shift | 删除开头 | |
unshift | 添加开头 | |
splice | 删除同时更新 | // 在位置2删除1个元素,添加2个元素 const arr = ['a', 'b', 'c', 'd']; arr.splice(2, 1, 'xx', 'yy'); >>> [ 'a', 'b', 'xx', 'yy', 'd' ] |
keys | 返回数组的可迭代对象,包含原始数组的键(key) | |
entires | 返回数组的可迭代对象 | |
sort | 顺序排序 | |
reverse | 逆序排序 | |
toString | 转字符串 | |
find | 返回符合传入测试(函数)条件的数组元素。 | // 获取第一个大于10的数 [10, 20, 30].find((e) => e > 10) >>> 20 |
findIndex | 返回符合传入测试(函数)条件的数组元素索引。 | // 获取第一个大于10的索引位置 [10, 20, 30].find((e) => e > 10) >>> 1 |
every | 遍历(检测数值元素的每个元素是否都符合条件。) | |
some | 遍历(检测数组元素中是否有元素符合指定条件。) | |
filter | 遍历(检测数值元素,并返回符合条件所有元素的数组。) | |
flat | 遍历(按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回) | |
form | 遍历(用于将两类对象转为真正的数组) | |
forEach | 遍历(数组每个元素都执行一次回调函数。) | |
reduece | 遍历(接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值) | |
reduceRight | 遍历(将数组元素计算为一个值(从右到左)。) | |
map | 遍历(通过指定函数处理数组的每个元素,并返回处理后的数组。) |
代码-数组长度更改
var arr = [];
/* 小技巧:数组长度更改 */
arr = [10, 20, 30, 40, 50];
arr.length = 2;
console.log(arr); // >>> [10,20]
代码-填充数组
[1, 2, 3, 4].fill('temp', 1, 3); // >>> [ 1, 'temp', 'temp', 4 ]
[1, 2, 3].fill(0); // >>> [ 0, 0, 0 ]
代码-Array.from
// 遍历
Array.from([1, 2, 3], (x) => x * x)
// >>> [1,4,9]
// 判断
Array.from([1, false, 2, true, 3], (n) => n || 0)
// >>> [ 1, 0, 2, true, 3 ] 布尔值为false的成员转为0
// 获取所有索引
Array.from(['a', 'b', 'c'].keys());
// >>> [0,1,2]
// 获取所有值
Array.from(['a', 'b', 'c'].values());
// >>> ['a','b','c']
// 键值对形式输出
Array.from(['a', 'b', 'c'].entries())
// >>> [ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ] ]
// 集合转数组
Array.from(new Set(['a', 'b', 'c']));
// >>> [ 'a', 'b', 'c' ]
// 对象转数组
Array.from({ '0': 'a', '1': 'b', '2': 'c', length: 2 /*固定写法*/ });
// ['a', 'b']
代码-扁平化
arr = [[1, 2], [3, 4, 5], [6, 7, 8, 9]];
// 方法1:展开运算符
[].concat(...arr);
// >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 方法2:concat和apply的组合
[].concat.apply([], arr);
// >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 方法3: flat方法
[1, [2, [3, 4]]].flat();
// >>> [ 1, 2, [ 3, 4 ] ]
[1, [2, [3, 4]]].flat(2);
// >>> [ 1, 2, 3, 4 ]
代码-自定义remove
Array.prototype.remove = function () {
for (var i = 0; i < arguments.length; i++) {
var ele = arguments[i];
var index = this.indexOf(ele);
if (index > -1) {
this.splice(index, 1);
}
}
};
代码-排序
// 排序
let array = [3, 9, 6];
array.sort();
array.reverse(); // 降序-必须先升序 才能降序
// 随机排序
let array1 = [30, 90, 60, 10, 20];
array1.sort(function (a, b) {
return 0.5 - Math.random()
});
集合
代码-常用方法
const set = new Set(['Ap', 'Bt', 'Cn']);
let isHas = set.has('Ap'); // 判断 >>> true
set.add('Add'); // 添加 >>> Set(4) { 'Ap', 'Bt', 'Cn', 'Add' }
set.delete('Bt'); // 删除 >>> Set(3) { 'Ap', 'Cn', 'Add' }
const res = Array.from(set); // 转换 >>> [ 'Ap', 'Cn', 'Add' ]
[...new Set([1, 2, 2, 3])] // 去重 >>> [1,2,3]
对象
代码-键排序
// 方法1
// 键值必须字符串格式
var obj = [
{ x: 'a', n: '456' },
{ x: 'c', n: '789' },
{ x: 'd', n: '123' }
];
obj.sort((a, b) => a.n.localeCompare(b.n));
// >>> [ { x: 'd', n: '123' }, { x: 'a', n: '456' }, { x: 'c', n: '789' } ]
// 方法2
var o = { 'a': 1, 'b': 3, 'c': 2 };
let keySorted = Object.keys(o).sort((a, b) => o[b] - o[a]);
// >>> [ 'b', 'c', 'a' ]
代码-键合并
var n1 = { name: '123', num: '' };
var n2 = { name: '456', num: '0', temp: '1' };
var n3 = { ...n1, ...n2 }; // >>> { name: '456', num: '0', temp: '1' }
代码-判断是否包含某键
var obj = { x: 1, y: 2 };
obj.hasOwnProperty('x') // 方法1 >>> true
'x' in obj // 方法2 >>> true
代码-判断是否为对象
// 方法1(推荐)
Object.prototype.toString.call(obj) === '[object Object]'
// 方法2
obj.constructor === Object
// 方法3
obj instanceof Object
类继承
代码-继承
class Language {
constructor(chinese, english) {
this.ch = chinese;
this.en = english;
}
}
class Word extends Language {
constructor(ch, en, type) {
super(ch, en);
this.type = type;
}
}
let d = new Word('中文', '英文', '类型');
console.log(d);
// >>> Word { ch: '中文', en: '英文', type: '类型' }
异常处理
代码-try/throw
/* try-catch 处理 */
{
const x = 0;
try {
x = 123;
console.log("error...");
} catch (e) {
console.log(e.message);
console.log(">>>catch");
} finally {
console.log("end....");
}
}
/* throw 处理 */
{
try {
var y = 0;
if (y < 1) throw new Error("small..");
} catch (err) {
console.log(err.message);
}
}
本地存储
代码-localStorage/SessionStoorage
// localStorage(永久) SessionStoorage(临时)
// 设置
window.localStorage.setItem(
"admin",
JSON.stringify(
{ "username": "apple", "id": "123456"}
)
);
// 接收
JSON.parse(
window.localStorage.getItem("admin")
);
// >>> {username: 'apple', id: '123456'}
// localStorage.removeItem("admin"); // 删除
// localStorage.clear(); // 清空
日期格式
代码-日期获取
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date();
var year = d.getFullYear(),
month = d.getMonth(),
day = d.getDate(),
hour = d.getHours(),
minutes = d.getMinutes();
console.log(year, month, day, hour, minutes); // 2023 8 30 11 16
console.log(d); // Thu Dec 01 2022 12:41:25 GMT+0800 (中国标准时间)
console.log(d.toDateString()); // Thu Dec 01 2022
console.log(d.toLocaleDateString()); // 2022/12/1
console.log(d.toLocaleTimeString()); // 12:41:25
console.log(d.toLocaleString()); // 2022/12/1 12:41:25
代码-获取两个日期之间的天数
const diffDays = (date, otherDate)
=> Math.ceil(
Math.abs(date - otherDate)
/ (1000 * 60 * 60 * 24)
);
var resDay = diffDays(new Date("2023-09-01"), new Date("2023-10-01"));
console.log(resDay) // >>> 30
URL编码
代码-encode/base64
/* encode编码 */
var site = "http://www.pt.com/?page=1&&keyword=图片";
var urlEn = encodeURI(site);
// >>> http://www.pt.com/?page=1&&keyword=%E5%9B%BE%E7%89%87
urlEn = decodeURI(urlEn);
var urlEn2 = encodeURIComponent(site);
// >>> http%3A%2F%2Fwww.pt.com%2F%3Fpage%3D1%26%26keyword%3D%E5%9B%BE%E7%89%87
urlEn2 = decodeURIComponent(urlEn2);
var urlEn3 = escape(site);
// >>> http%3A//www.pt.com/%3Fpage%3D1%26%26keyword%3D%u56FE%u7247
urlEn3 = unescape(urlEn3);
/* base64编码 */
var base64 = btoa("id=123456"); // 编码
// >>> aWQ9MTIzNDU2
base64 = atob(base64); // 解码
Math
max | 最大值 |
min | 最小值 |
random | 0~1随机数 |
abs | 绝对值 |
pow | pow(x,y) x的y次幂 |
sqrt | sqrt(x) x的平方根 |
log | log(x) x的自然对数(底为e) |
log10 | 以10为底的对数 |
log2 | 以2为底的对数 |
cos | 余弦 |
sin | 正弦 |
tan | 正切 |
ceil | 向上舍入 |
floor | 向下舍入 |
round | 四舍五入 |
Cookie
代码-自定义cookie
// 提示:Cookie是4k,Web Storage为5M
/* 参数列表 */
{
/**
* @param cookie
* 用户认证的一种方式
* ---------------------------------------------------------------
* @param title 了解
* 浏览器发送请求时,会自动携带cookie,发送到服务端
* cookie在浏览器关闭后就会被清除
* cookie最多4kb左右大小
* cookie键与值必须使用英文
* cookie以键值对形式存储
* @param object
* name 名称
* expires 设置cookie的失效时间,值是Data类型
* max-age 设置cookie的失效时间,
值是数字,单位秒(如果值为0或者负数,表示删除该cookie)
* domain 设置可以访问cookie的域名(不常用,了解即可)
* path 设置cookie的路径,限定访问Cookie的范围
* httpOnly 设置httpOnly属性的cookie不能通过js访问
* secure 安全标志,如果设置了这个属性,只在安全协议时,
如:https,才会将cookie发送到服务端
*/
}
/* 设置cookie */
const setCookie = (key, value, day) => {
const d = new Date();
d.setDate(d.getDate() + day);
document.cookies = `${key}=${value};expires=${d.toUTCString()}`;
};
setCookie("test", "123456", 3);
console.log(document.cookies);
// time:9/30 +3天 = 10/3 >>> test=123456;expires=Tue, 03 Oct 2023 04:45:40 GMT
/* cookie有效期 */
{
// 设置
function set(name, value, day) {
let d = new Date(),
time = 0;
// 默认存储1天
day = typeof day === "undefined" || !day ? 1 : day;
// 毫秒
time = d.setHours(d.getHours() + 24 * day);
localStorage.setItem(name, JSON.stringify({ data: value, time: time }));
}
// 获取
function get(name) {
let data = localStorage.getItem(name);
if (!data) {
return null;
}
let obj = JSON.parse(data);
// 过期
if (new Date().getTime() > obj.time) {
localStorage.removeItem(name);
return null;
} else {
return obj.data;
}
}
// 删除缓存(清空)
function clear(name) {
if (name) {
// 删除键为name的缓存
localStorage.removeItem(name);
} else {
// 清空全部
localStorage.clear();
}
}
set("abc", "111");
console.log(get("abc")); // >>> 111
// clear("abc"); // >>> 清空
console.log(localStorage); // >>> {"data":"111","time":1696137671050}
}
正则表达式
i | 大小写不敏感 |
g | 执行全局匹配 |
m | 执行多行匹配 |
exec | 检索字符串中指定的值。返回找到的值, 并确定其位置 |
test | 检索字符串中指定的值。返回 true 或 false |
compile | compile() 方法用于改变 RegExp(把 pattern 转换为内部的格式,从而执行得更快)/方法用于在脚本执行过程中编译正则表达式。 语法: str.compile(匹配模式); |
search | search() 方法使用表达式来搜索匹配,然后返回匹配的位置 |
match | match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。 |
b | B | 单词边界 | 非单词边界 |
d | D | 数字 | 非数字 |
s | S | 空白字符 | 非空白字符 |
w | W | 单词字符 | 非单词字符 |
[0 - 9] | 0 到 9之间任意数字 |
[A - z] | 全部大小写字母 |
[a - z] | 小写字母 |
[abc] | 查找方括号之间的任何字符。 |
[^ abc] | 查找任何不在方括号之间的字符 |
/[\u4e00-\u9fa5]/g | 匹配中文 |
代码-常用方法
var str = "";
str = "金木水火土12345ABCDE!@#$%&*.png//###./";
str.search(/木/i); // >>> 1
str.match(/\d/g); // >>> ['1','2','3','4','5'];
str.match(/[土]/g); // >>> 土
str.match(/[^土]/g); // >>> 全部显示(土除外)
str = "10_aA_100_bBB_1000_cCCC_10000_dDDDD.com";
res = str.match(/10/g); // >>> ['10', '10', '10', '10']
str.match(/10+/g); // >>> ['10', '100', '1000', '10000'] // 【参数:n+】 量词匹配包含至少一个n的任何字符串
str.match(/cC*/g); // >>> ['cCCC', 'c'] // 【参数:*】 匹配任何包含零个或多个 n 的字符串
str.match(/cC?/g); // >>> ['cC', 'c'] // 【参数:?】 匹配任何包含零个或一个 n 的字符串
str.match(/./g); // >>> 显示所有 // 【参数:.】 查找单个字符,除了换行和行结束符
str.match(/1000.*10000/g); // >>> ['1000_cCCC_10000'] // 【参数:.*】 懒惰匹配
str.match(/\d{4}/g); // >>> ['1000', '1000'] // 匹配n个数量
str.match(/\d{3,4}/g); // >>> ['100', '1000', '1000'] // 匹配n1~n2之间数量
str.match(/\d{4,}/g); // >>> ['100', '1000', '1000'] // 匹配最少n个数量
str.match(/^\d/g); // >>> ['1'] // 匹配开头
str.match(/\w{3}$/g); // >>> ['com'] // 匹配结尾
str.match(/\w{3}(?=.com)/g); // >>> ['DDD'] // 【参数:?=n|?!n】 匹配任何其后紧接指定字符串|没有紧接的字符串
str.match(/\w+(?=.com)/g); // >>> ['10_aA_100_bBB_1000_cCCC_10000_dDDDD', 'com'];
// 判断
var patt1 = new RegExp("c");
console.log(patt1.test("abcd")); // >>> true
patt1.compile("d");
console.log(patt1.test("abc")); // >>> false
lxml
代码-基本用法
<!--
【简介】
XML指,可扩展性标记语言
XML标签必须自定义(推荐英文单词,方便直观理解)
【特点】
规定数据格式,具有结构性,易读易处理
【应用】
用于配置文件/存储数据(小型数据库)
【格式】
xml格式: 根节点 root(固定写法)
<?xml version='1.0' encoding='utf-8' ?> // xml文件头声明(可选项)
-->
<root>
<user>杰克</user>
<msg>这是一个美国人物</msg>
</root>
<!--
xml属性:一个标签可以有多个属性,属性值必须引号
<name age='18' > 太白 /name>
-->