结尾
学习html5、css、javascript这些基础知识,学习的渠道很多,就不多说了,例如,一些其他的优秀博客。但是本人觉得看书也很必要,可以节省很多时间,常见的javascript的书,例如:javascript的高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。
=============================================================================
此方法用于获取两个数字之间的随机整数。
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
console.log( random(1, 50) )// 25
console.log( random(1, 50) )// 34
================================================================================
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, © => c.toUpperCase())
console.log( uppercaseWords(‘hello world’) ); // ‘Hello World’
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
console.log( capitalize(“hello world”));// ‘Hello world’
=========================================================================
删除数组的重复项是非常有必要的,使用“Set”会变得非常简单。
const removeDuplicates = (arr) => […new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]))
// [1, 2, 3, 4, 5, 6]
==========================================================================
删除数组对象中重复项
const CSDN = [
{
id: ‘1’,
result: ‘半’
},
{
id: ‘1’,
result: ‘半’
},
{
id: ‘2’,
result: ‘生’
},
{
id: ‘3’,
result: ‘生’
},
{
id: ‘3’,
result: ‘过’
},
{
id: ‘3’,
result: ‘往’
},
{
id: ‘4’,
result: ‘往’
},
]
let obj = {}
let scdn = CSDN.reduce((cur,next) => {
obj[next.id] ? “” : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(scdn );
// 0: {id: ‘1’, result: ‘半’}
// 1: {id: ‘2’, result: ‘生’}
// 2: {id: ‘3’, result: ‘生’}
// 3: {id: ‘4’, result: ‘往’}
// length: 4
======================================================================
多层数组展开成一层
// 方法一:
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)
// 方法二:
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? […a, …flat(b)] : […a, b]), [])
console.log( flat([‘半’, [‘生’, ‘过’, [‘往’]]]) );
// [‘半’, ‘生’, ‘过’, ‘往’]
=========================================================================
使用此方法,您将能够过滤掉数组中的所有虚假值。
const removeFalsy = (arr) => arr.filter(Boolean)
console.log( removeFalsy([0, ‘a string’, ‘’, NaN, true, 5, undefined, ‘another string’, false]) )
// [‘a string’, true, 5, ‘another string’]
=============================================================================
可以通过使用模运算符 (%) 来解决。
const isEven = num => num % 2 === 0
console.log( isEven(2) )// true
console.log( isEven(1) )// false
========================================================================
我们可以使用 reduce 方法来获取我们在此函数中提供的参数的平均值。
const average = (…args) => args.reduce((a, b) => a + b) / args.length;
console.log( average(1, 2, 3, 4, 5); ) // 3
const arr = [0, 1, 2, 3];
const min = Math.min(…arr); // 0
const max = Math.max(…arr); // 3
===========================================================================
使用 Math.pow() 方法,我们可以将一个数字截断为我们在函数中提供的某个小数点。
const round = (n, d) => Number(Math.round(n + “e” + d) + “e-” + d)
console.log( round(1.005, 2) ) //1.01
console.log( round(1.555, 2) ) //1.56
console.log( round(1.554, 2) ) //1.55
console.log( round(1.555, 3) ) //1.555
console.log( round(1.555, 1) ) //1.6
===========================================================================
计算两个日期之间的天数,一行代码就可以搞定。
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
console.log( diffDays(new Date(“2021-11-3”), new Date(“2022-2-1”)) )// 100
==============================================================================
您想知道某个日期是一年中的哪一天吗?
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
console.log( dayOfYear(new Date()) ) // 101
const isWeekend = (date) => [0, 6].indexOf(date.getDay()) !== -1;
console.log(isWeekend(new Date(2022, 4, 15)));
// false (Friday)
console.log(isWeekend(new Date(2022, 4, 16)));
// true (Saturday)
使用以下代码段检查给定日期是否有效。
const isDateValid = (…val) => !Number.isNaN(new Date(…val).valueOf());
const isDateValid = (…val) => !Number.isNaN(new Date(…val).valueOf());
console.log(isDateValid(“December 17, 1995 03:24:00”)); // true
console.log(isDateValid(“1995.08.04 03:24:00”)); // true
console.log(isDateValid(“1995/08/04 03:24:00”)); // true
console.log(isDateValid(“1995/08/04 T 03:24:00”)); // aflse
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// 17:30:00
==============================================================================
如果你需要一个随机的颜色值,这个函数就可以了。
const randomColor = () => #${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}
console.log( randomColor() )// #9dae4f
console.log( randomColor() )// #6ef10e
==============================================================================
const rgbToHex = (r, g, b) => “#” + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
console.log( rgbToHex(255, 255, 255) ) // ‘#ffffff’
============================================================================
const clearCookies = () => document.cookie.split(‘;’).forEach(© => (document.cookie = c.replace(/^ +/, ‘’).replace(/=.*/, =;expires=${new Date().toUTCString()};path=/
)))
========================================================================
根据某些特征对数组进行分组
const groupBy = (arr, fn) =>
arr.map(fn).reduce((acc, cur, i) => {
acc[cur] = […(acc[cur] || []), arr[i]];
return acc;
}, {});
console.log( groupBy([1, “2”, 3, “4”],(val) => typeof val) )
//{ number: [ 1, 3 ], string: [ ‘2’, ‘4’ ] }
console.log( groupBy([[1], [1,2], [3], [3,4]], (val) => typeof val.length) );
// { 1: [ [ 1 ], [ 3 ] ], 2: [ [ 1, 2 ], [ 3, 4 ] ] }
===============================================================================
const getValue = (from, selectors) =>
selectors
.replace(/[([1*)]/g, ‘.$1.’)
.split(‘.’)
.filter((item) => item !== ‘’)
.reduce((acc, cur) => {
if (acc instanceof Object) {
return acc[cur];
}
return void 0;
}, from);
const object = { a: [{ b: { c: 3 } }] };
const array = [{ a: { b: [1] } }, { c: 2 }];
console.log(getValue(object, ‘a[0].b.c’));
// 3
console.log(getValue(array, ‘[0].a.b[0]’));
// 1
console.log(getValue(array, ‘[1].c’));
// 2
console.log(getValue(array, ‘[0].a.b[0][2].c’));
// undefined
====================================================================
深拷贝功能考虑了几乎各种极端情况
const deepClone = (obj, map = new WeakMap()) => {
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (map.has(obj)) {
return map.get(obj);
}
const allDesc = Object.getOwnPropertyDescriptors(obj);
const cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
map.set(obj, cloneObj);
for (const key of Reflect.ownKeys(obj)) {
const value = obj[key];
cloneObj[key] =
value instanceof Object && typeof value !== ‘function’
-
? deepClone(value, map)
- value;
}
return cloneObj;
};
const symbolKey = Symbol(‘symbolKey’);
const originValue = {
num: 0,
str: ‘’,
boolean: true,
unf: void 0,
nul: null,
obj: { name: ‘object’, id: 1 },
arr: [0, 1, 2],
func() {
console.log(‘function’);
},
date: new Date(0),
reg: new RegExp(‘/regexp/ig’),
};
Object.defineProperty(originValue, ‘innumerable’, {
// writable is true to ensure that the assignment operator can be used
writable: true,
enumerable: false,
value: ‘innumerable’,
});
// Create circular reference
originValue.loop = originValue;
// Deep Copy
const clonedValue = deepClone(originValue);
// Change original value
originValue.arr.push(3);
originValue.obj.name = ‘newObject’;
// Remove circular reference
originValue.loop = ‘’;
originValuesymbolKey = ‘newSymbol’;
console.log('originValue: ', originValue);
console.log('clonedValue: ', clonedValue);
============================================================================
从 URL 获取参数
const getURLParams = (url) => {
return (url.match(/([?=&]+)(=([&]*))/g) || []).reduce((acc, cur) => {
const [k, v] = cur.split(‘=’);
const p = acc[k];
acc[k] = p ? (Array.isArray§ ? p : [p]).concat(v) : v;
return acc;
}, {});
};
console.log(getURLParams(‘google.com’));
// {}
console.log(getURLParams(‘https://www.google.com/?name=1&age=2’));
// { name: ‘1’, age: ‘2’ }
// 支持数组格式
console.log(getURLParams(‘https://www.google.com/?name=1&age=2&age=3’));
// { name: ‘1’, age: [ ‘2’, ‘3’ ] }
console.log(getURLParams(‘name=1&age=2’));
// { name: ‘1’, age: ‘2’ }
或者更直接的
console.log(Object.fromEntries(new URLSearchParams(window.location.search)));
====================================================================================
// 方法 1
function formatMoney(num) {
return num.toLocaleString();
}
// 方法 2
function formatMoney(num) {
const nf = new Intl.NumberFormat();
return nf.format(num);
}
//方法 3
function formatMoney(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ‘,’);
}
// 方法 4
function formatMoney(num) {
const arr = num.toString().split(‘’);
let index = -3;
while (arr.length + index > 0) {
arr.splice(index, 0, ‘,’);
index -= 4;
}
return arr.join(‘’);
}
console.log(‘20220415’ + formatMoney(20220316));
// ‘20,220,316’
小数部分必须为2位,不足2位补零,多于2位四舍五入
const numFormat = new Intl.NumberFormat(‘zh-CN’, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
/**
-
整数部分每3位用逗号分割。
-
小数部分必须为2位,不足2位补零,多于2位四舍五入
*/
function formatCurrency(number) {
return numFormat.format(number);
}
// 测试0
console.log(‘0转换成’ + formatCurrency(0));
console.log(‘-0转换成’ + formatCurrency(-0));
console.log(‘0.0转换成’ + formatCurrency(0.0));
console.log(‘-0.0转换成’ + formatCurrency(-0.0));
// 测试1位整数
console.log(‘3转换成’ + formatCurrency(3));
console.log(‘-3转换成’ + formatCurrency(-3));
// 测试3位整数
console.log(‘123转换成’ + formatCurrency(123));
console.log(‘-123转换成’ + formatCurrency(-123));
// 测试5位整数
console.log(‘12345转换成’ + formatCurrency(12345));
console.log(‘-12345转换成’ + formatCurrency(-12345));
// 测试7位整数
console.log(‘1234567转换成’ + formatCurrency(1234567));
console.log(‘-1234567转换成’ + formatCurrency(-1234567));
// 测试1位小数
console.log(‘12345.3转换成’ + formatCurrency(12345.3));
console.log(‘-12345.3转换成’ + formatCurrency(-12345.3));
// 测试2位小数
console.log(‘12345.34转换成’ + formatCurrency(12345.34));
console.log(‘-12345.34转换成’ + formatCurrency(-12345.34));
// 测试3位小数
console.log(‘12345.344转换成’ + formatCurrency(12345.344));
console.log(‘-12345.344转换成’ + formatCurrency(-12345.344));
console.log(‘12345.345转换成’ + formatCurrency(12345.345));
console.log(‘-12345.345转换成’ + formatCurrency(-12345.345));
======================================================================
将字节转换为可读文本时
const formatBytes = (bytes, decimals = 2) => {
if (bytes < 0) return ‘’;
if (bytes <= 1) return ${bytes}B
;
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = [‘B’, ‘KB’, ‘MB’, ‘GB’, ‘TB’, ‘PB’, ‘EB’, ‘ZB’, ‘YB’];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return ${parseFloat((bytes / k ** i).toFixed(dm))}${sizes[i]}
;
};
console.log(formatBytes(1024));
// 1KB
console.log(formatBytes(1024 ** 2));
// 1MB
console.log(formatBytes(1024 ** 3));
// 1GB
console.log(formatBytes(1024 ** 4));
// 1TB
==================================================================================
将变量嵌入到 HTML 中,然后,通过函数将这些字符串转换成真实的 DOM
// 方法 1
const str2DOM = (str) => {
const div = document.createElement(‘div’);
div.innerHTML = str;
return div.firstElementChild;
}
// 方法 2
const str2DOM = (str) => {
return new DOMParser().parseFromString(str, ‘text/html’).body
.firstElementChild;
}
最后
编程基础的初级开发者,计算机科学专业的学生,以及平时没怎么利用过数据结构与算法的开发人员希望复习这些概念为下次技术面试做准备。或者想学习一些计算机科学的基本概念,以优化代码,提高编程技能。这份笔记都是可以作为参考的。
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
] ↩︎