过滤数组空值
// 过滤空字符串、null、undefined、0、false
const arr = ["apple", null, "milk", undefined, "bread", "", 0, false];
const list = arr.filter(Boolean);脚本
技巧、工具函数与常见校验,日常开发随手查。 — 共 41 条
共 41 条代码片段
// 过滤空字符串、null、undefined、0、false
const arr = ["apple", null, "milk", undefined, "bread", "", 0, false];
const list = arr.filter(Boolean);const people = [
{ name: "a", age: 20 },
{ name: "b", age: 22 },
{ name: "c", age: 60 },
];
const [{ age }] = people; // 20+new Date();
+new Date();
new Date() * 1;
new Date().valueOf();
new Date().getTime();~~2.33; // 2
2.33 | 0; // 2
2.33 >> 0; // 2Number(parseFloat(2.345).toFixed(3).slice(0, -1)); // 2.34let a = 1,
b = 2;
a ^= b;
b ^= a;
a ^= b;const randomBoolean = () => Math.random() >= 0.5;// 方法 1:有缺陷,方法等会丢失
const newObj = JSON.parse(JSON.stringify(obj));
// 方法 2
function clone(obj) {
if (obj === null) return null;
if (typeof obj !== "object") return obj;
if (obj.constructor === Date) return new Date(obj);
if (obj.constructor === RegExp) return new RegExp(obj);
const result = new obj.constructor();
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const val = obj[key];
result[key] = typeof val === "object" ? clone(val) : val;
}
}
return result;
}!!myObj["someProperty"]; // 无法判断 {}、[]
"someProperty" in myObj; // 会判断原型链
myObj.hasOwnProperty("someProperty"); // 不考虑原型链// ES5
const obj = Object.assign({}, obj1, obj2);
// ES6
const obj2 = { ...obj1, ...obj2 };// ES5
const arr = arrA.concat(arrB);
// ES6 去重合并
const arr2 = [...new Set([...arrA, ...arrB])];Math.random().toString(16).substring(2); // 13 位
Math.random().toString(36).substring(2); // 11 位str.split("").reverse().join("");"风起云涌".replace(/.(?=.)/g, "*"); // ***涌
phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2"); // 131****5678/**
* 手机号格式化
* 13012345678 => 130-1234-5678
*/
const formatMobile = (phone, symbol = "-") => {
if (typeof phone === "number") phone = phone.toString();
return phone.replace(
/(\d{3})(\d{4})(\d{4})/,
"$1" + symbol + "$2" + symbol + "$3"
);
};// 4 位分隔 1234 5678 9123 123
val.replace(/\s/g, "").replace(/([0-9]{4})(?=[0-9])/g, "$1 ");[...new Set([1, "1", 2, 1, 1, 3])]; // [1, "1", 2, 3]
function unique(arr) {
const map = new Map();
const result = [];
for (let i = 0, len = arr.length; i < len; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], true);
result.push(arr[i]);
}
}
return result;
}function getArrDifference(arr1, arr2) {
return arr1.concat(arr2).filter(function (v, i, arr) {
return arr.indexOf(v) === arr.lastIndexOf(v);
});
}function getArrEqual(arr1, arr2) {
const newArr = [];
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if (arr1[j] === arr2[i]) newArr.push(arr1[j]);
}
}
return newArr;
}const numbers = [5, 458, 120, -215, 228, 400, 122205, -85411];
Math.max.apply(Math, numbers); // 122205
Math.min.apply(Math, numbers); // -85411
// 或
Math.max(...numbers);
Math.min(...numbers);function swapArr(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
}function toFirst(fieldData, index) {
if (index !== 0) {
fieldData.unshift(fieldData.splice(index, 1)[0]);
}
}function isRepeat(arr) {
const hash = {};
for (const i in arr) {
if (hash[arr[i]]) return true;
hash[arr[i]] = true;
}
return false;
}// 判断 index 是否小于 0
index = Math.max(0, --index);
// 判断 index 是否大于 len
index = Math.min(len, ++index);console.time("Timer");
const arr = [];
for (let i = 0; i < 50; i++) {
arr.push(i);
}
console.timeEnd("Timer");const isWeekday = (date) => date.getDay() % 6 !== 0;const goToTop = () => window.scrollTo(0, 0);
goToTop();function getUrlParam(name) {
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
const r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}function cutString(str, len) {
if (!str) return "";
if (str.length <= len) return str;
return str.substring(0, len) + "...";
}function removeHtml(str) {
return str.replace(/<[^>]+>/g, "");
}function pad(num, n = 2) {
let len = num.toString().length;
while (len < n) {
num = "0" + num;
len++;
}
return num;
}function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}function setLocal(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function getLocal(key) {
const val = localStorage.getItem(key);
try {
return JSON.parse(val);
} catch {
return val;
}
}
function removeLocal(key) {
localStorage.removeItem(key);
}function typeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
// typeOf([]) => "array"
// typeOf({}) => "object"
// typeOf(null) => "null"function checkMobile(val) {
return /^1[3-9]\d{9}$/.test(val);
}function checkQQ(val) {
return /^[1-9][0-9]{4,10}$/.test(val);
}function checkWechat(val) {
return /^[a-zA-Z][-_a-zA-Z0-9]{5,19}$/.test(val);
}function checkEmail(val) {
return /^[\w.-]+@[\w.-]+\.\w+$/.test(val);
}function checkIdCard(val) {
return /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/.test(val);
}function checkChinese(val) {
return /^[\u4e00-\u9fa5]+$/.test(val);
}function checkImage(val) {
return /\.(gif|jpg|jpeg|png|bmp|webp)$/i.test(val);
}