js 小技巧
MDN 快速搜索
Section titled “MDN 快速搜索”字符串转数组
Section titled “字符串转数组”const str = "asdfghjkl";
str.split(""); // ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']Array.from(str); // ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'][...str]; // ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']Array.of(...str); // ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']Object.values(str); // ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']数组转字符串
Section titled “数组转字符串”const arr = ["a", "s", "d", "f", "g", "h", "j", "k", "l"];
arr.join(""); // 'asdfghjkl'"".concat(...arr); // 'asdfghjkl'arr.toString(); // 'a,s,d,f,g,h,j,k,l'arr.toLocaleString(); // 'a,s,d,f,g,h,j,k,l'arr + []; // 'a,s,d,f,g,h,j,k,l'arr + ""; // 'a,s,d,f,g,h,j,k,l'// 拓展:join() 和 toString() 都可以将多维数组转成普通字符串。const arr = [1, [2, 3], [4, 5]];arr.join(); // '1,2,3,4,5'arr.toString(); // '1,2,3,4,5'Array.prototype.map()
Section titled “Array.prototype.map()”// 字符串数组转换为数值型数组let arr = [1, 2, 3];arr.map(String); // ['1', '2', '3']
// 数值数组转换为字符串型数组arr = ["1", "2", "3"];arr.map(Number); // [1, 2, 3]
// 数值型数组转换为布尔值arr = [0, 1, 1, 1, 0];arr.map(Boolean); // [false, true, true, true, false]
// 混合类型转换对比arr = [1, 0, "1", "-1", "0", true, false, "true", "false", null, undefined, Number.NaN, ""];arr.map(String);// ['1', '0', '1', '-1', '0', 'true', 'false', 'true', 'false', 'null', 'undefined', 'NaN', '']arr.map(Number);// [1, 0, 1, -1, 0, 1, 0, NaN, NaN, 0, NaN, NaN, 0]arr.map(Boolean);// [true, false, true, true, true, true, false, true, true, false, false, false, false]Array.prototype.filter()
Section titled “Array.prototype.filter()”// 移除所有的 “false” 类型元素(false, null, undefined, 0, NaN, an empty string)const arr = [1, 0, false, "true", {}, null, undefined, Number.NaN, "", , "false"];arr.filter(Boolean); // [1, 'true', {}, 'false']JSON.parse()
Section titled “JSON.parse()”JSON.parse("true"); // trueJSON.parse("false"); // falseJSON.parse(true); // trueJSON.parse(false); // falseJSON.stringify()
Section titled “JSON.stringify()”const obj = { a: 1, b: [ { a: 2, }, ],};
console.log(JSON.stringify(obj, ["b"], 2)); // 过滤console.log(JSON.stringify(obj, null, 2));// node 环境console.dir(obj, { showHidden: false, depth: 99, colors: true,});模板字符串嵌套
Section titled “模板字符串嵌套”const a = 20;const b = 30;const c = "三";const d = "日";const res = `今天星期${Math.random() > 0.5 ? `${c}` : `${d}`},签到人数${Math.random() > 0.5 ? `${a}` : `${b}`}人`;console.log(res);多属性字符串拼接
Section titled “多属性字符串拼接”// 借助 Object.values()const obj = { a: "vue", b: "", c: "router", d: "react", e: "", f: "redux",};Object.values(obj).filter(Boolean).join("-");// 'vue-router-react-redux'给方法传一个空参数
Section titled “给方法传一个空参数”method(...["parameter1", , "parameter3"]);对象数组过滤出指定属性
Section titled “对象数组过滤出指定属性”const foo = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
foo.map((i) => i.id); // [1, 2, 3, 4, 5]const foo = [ { id: 1, children: [{ id: 1 }, { id: 2 }], }, { id: 2, children: [{ id: 3 }, { id: 4 }], },];
foo.flatMap((i) => i.children.map((i) => i.id)); // [1, 2, 3, 4]对象过滤掉指定参数
Section titled “对象过滤掉指定参数”const obj = { id: "1", name: "tom", age: 12,};const { id, ...rest } = obj;console.log(rest); // { name: 'tom', age: 12 }数据类型判断
Section titled “数据类型判断”- typeof
- instanceof
- Object.prototype.toString()
- 返回的数据格式为
[object Object]类型,可通过这一特点进行任意类型判断。
- 返回的数据格式为
// 任意数据类型判断function typeJudgment(variable) { return Object.prototype.toString.call(variable).slice(8, -1);}
typeJudgment(); // 'Undefined'typeJudgment(null); // 'Null'typeJudgment(true); // 'Boolean'typeJudgment(""); // 'String'typeJudgment(1); // 'Number'typeJudgment({}); // 'Object'typeJudgment([]); // 'Array'typeJudgment(() => {}); // 'Function'typeJudgment(new Date()); // 'Date'typeJudgment(/a/); // 'RegExp'typeJudgment(BigInt(1)); // 'BigInt'typeJudgment(Symbol(1)); // 'Symbol'async/await 异常捕获
Section titled “async/await 异常捕获”(async () => { // promise 返回值 const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve("success"); }); }); }; // 抽离公共方法 const awaitWrap = (promise) => { return promise.then((data) => [null, data]).catch((err) => [err, null]); };
const [err, data] = await awaitWrap(fetchData()); console.log(err, data);})();for…of 中使用索引
Section titled “for…of 中使用索引”const arr = [ { id: 1, name: "foo" }, { id: 2, name: "bar" },];
for (const [index, item] of arr.entries()) { console.log(index, item);}随机生成数组
Section titled “随机生成数组”生成随机元素填充,可能重复
Section titled “生成随机元素填充,可能重复”Array.from({ length: 9 }) .fill(0) .map(() => ~~(Math.random() * 9 + 1));唯一元素随机排序
Section titled “唯一元素随机排序”Array.from({ length: 9 }) .fill(0) .map((_, index) => index + 1) .sort(() => Math.random() - 0.5);String.raw
Section titled “String.raw”const rawString = String.raw`Hello\nWorld!`;console.log(rawString); // Hello\nWorld!const num = 42;rawString = String.raw`The number is ${num}\n!`;console.log(rawString); // The number is 42\n!Function.prototype.before
Section titled “Function.prototype.before”Function.prototype.before = function (beforeFn) { const __self = this; return function () { beforeFn.apply(this, arguments); return __self.apply(this, arguments); };};let func = function (param) { console.log(param);};
func = func.before(function (param) { param.b = "b";});
func({ a: "a" });// {a: "a", b: "b"}Function.prototype.after
Section titled “Function.prototype.after”Function.prototype.after = function (afterFn) { const __self = this; return function () { const ret = __self.apply(this, arguments); afterFn.apply(this, arguments); return ret; };};let func = function (param) { console.log(param);};
func = func.after(function (param) { param.b = "b"; console.log(param);});
func({ a: "a" });// {a: 'a'}// {a: 'a', b: 'b'}