GGbond为你手写了21个ES6规范的JS函数,每段代码都有注释与打印 , 你可以参考学习或者自己尝试实现。这些代码也是面试中经常被问到的 , 所有代码都使用es6规范 , 希望你能从中受益,提高你的JS水平。
1. 数组去重
const uniqueArray = (arr) => {
const set = new Set(arr);
return [...set];
};
console.log(uniqueArray([1, 2, 2, 3, 3])); // [1, 2, 3]
使用ES6的Set数据结构,将数组转换为Set,并通过展开运算符将其转换回数组,实现数组去重。
2. 将字符串转换为数字
const strToNum = (str) => {
const num = +str;
console.log(num);
return num;
};
strToNum('123'); // 123
使用一元加操作符,将字符串转换为数字。
3. 将数字转换为字符串
const numToStr = (num) => {
const str = num.toString();
console.log(str);
return str;
};
numToStr(123); // '123'
使用数字对象的toString()方法将数字转换为字符串。
4. 检查对象是否为空
const isObjEmpty = (obj) => {
const keys = Object.keys(obj);
const isEmpty = keys.length === 0 && obj.constructor === Object;
console.log(isEmpty);
return isEmpty;
};
isObjEmpty({}); // true
isObjEmpty({ a: 1 }); // false
使用Object.keys()方法获取对象的键数组,如果数组长度为0并且对象的构造函数为Object,则判断该对象为空。
5. 检查两个数组是否相等
const isEqual = (arr1, arr2) => {
const str1 = JSON.stringify(arr1);
const str2 = JSON.stringify(arr2);
const isEqual = str1 === str2;
console.log(isEqual);
return isEqual;
};
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [3, 2, 1]); // false
使用JSON.stringify()方法将数组转换为字符串,然后比较两个字符串是否相等,从而判断两个数组是否相等。
6. 将对象转换为URL参数
const objToUrlParam = (obj) => {
const params = Object.entries(obj).map(([key, val]) => `${key}=${encodeURIComponent(val)}`);
const urlParam = params.join('&');
console.log(urlParam);
return urlParam;
};
objToUrlParam({ name: 'John Doe', age: 30 }); // 'name=John%20Doe&age=30'
使用Object.entries()方法获取对象的键值对数组,然后使用map()方法将其转换为URL参数格式,并使用encodeURIComponent()方法将值编码,最后使用join()方法将各参数连接起来。
7. 将URL参数转换为对象
const urlParamToObj = (param) => {
const searchParams = new URLSearchParams(param);
const obj = Object.fromEntries(searchParams);
console.log(obj);
return obj;
};
urlParamToObj('name=John%20Doe&age=30'); // { name: 'John Doe', age: '30' }
使用URLSearchParams()方法将URL参数转换为对象,然后使用Object.fromEntries()方法将其转换为对象。
8. 获取随机整数
const getRandomInt = (min, max) => {
const randomInt = Math.floor(Math.random() * (max - min + 1) + min);
console.log(randomInt);
return randomInt;
};
getRandomInt(1, 10); // Random integer between 1 and 10
使用Math.random()方法生成0到1之间的随机数,然后使用Math.floor()方法将其转换为整数,并根据min和max值生成指定范围内的整数。
9. 获取随机浮点数
const getRandomFloat = (min, max) => {
const randomFloat = Math.random() * (max - min) + min;
console.log(randomFloat);
return randomFloat;
};
getRandomFloat(1.0, 10.0); // Random float between 1.0 and 10.0
使用Math.random()方法生成0到1之间的随机数,然后根据min和max值生成指定范围内的浮点数。
10. 数组扁平化
const flatten = (arr) => {
const flatArr = arr.flat(Infinity);
console.log(flatArr);
return flatArr;
};
flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4]
使用数组的flat()方法,将多维数组扁平化为一维数组。flat()方法接受一个参数,表示要扁平化的层数,如果不传参数,则默认扁平化所有层级。在本例中,我们使用Infinity表示要扁平化所有层级。
11. 获取最大值
const getMax = (arr) => {
const max = Math.max(...arr);
console.log(max);
return max;
};
getMax([1, 2, 3]); // 3
使用展开运算符将数组展开为多个参数,并使用Math.max()方法获取最大值。
12. 获取最小值
const getMin = (arr) => {
const min = Math.min(...arr);
console.log(min);
return min;
};
getMin([1, 2, 3]); // 1
使用展开运算符将数组展开为多个参数,并使用Math.min()方法获取最小值。
13. 扁平化多维数组
const flatten = (arr) => {
const flatArr = [].concat(...arr.map((val) => (Array.isArray(val) ? flatten(val) : val)));
console.log(flatArr);
return flatArr;
};
flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4]
使用递归函数,将多维数组扁平化为一维数组。
14. 数组并集
const union = (arr1, arr2) => {
const set = new Set([...arr1, ...arr2]);
const unionArr = [...set];
console.log(unionArr);
return unionArr;
};
union([1, 2, 3], [2, 3, 4]); // [1, 2, 3, 4]
使用Set数据结构和展开运算符,将两个数组合并,并使用Set去重。
15. 数组交集
const intersection = (arr1, arr2) => {
const intersectionArr = arr1.filter((val) => arr2.includes(val));
const set = new Set(intersectionArr);
const uniqueArr = [...set];
console.log(uniqueArr);
return uniqueArr;
};
intersection([1, 2, 3], [2, 3, 4]); // [2, 3]
使用Set数据结构和数组的filter()方法,将两个数组的交集提取出来,并使用Set去重。
16. 数组差集
const difference = (arr1, arr2) => {
const differenceArr = arr1.filter((val) => !arr2.includes(val));
const set = new Set(differenceArr);
const uniqueArr = [...set];
console.log(uniqueArr);
return uniqueArr;
};
difference([1, 2, 3], [2, 3, 4]); // [1]
使用Set数据结构和数组的filter()方法,将两个数组的差集提取出来,并使用Set去重。
17. 柯里化
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length ? fn(...args) : (...rest) => curried(...args, ...rest);
console.log(curried);
return curried;
};
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
使用递归函数,将接受多个参数的函数转换为逐个接受参数的函数。
18. 防抖
const debounce = (fn, delay) => {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
const log = () => console.log('Hello World!');
const debouncedLog = debounce(log, 1000);
debouncedLog(); // This will log "Hello World!" after 1 second
使用setTimeout()方法,延迟一定时间后执行函数,并使用clearTimeout()方法清除计时器,从而实现防抖。
19. 节流
const throttle = (fn, interval) => {
let lastTime = 0;
return function (...args) {
const now = new Date().getTime();
if (now - lastTime >= interval) {
lastTime = now;
fn.apply(this, args);
}
};
};
const log = () => console.log('Hello World!');
const throttledLog = throttle(log, 1000);
throttledLog(); // This will log "Hello World!" immediately, and then every 1 second
使用Date对象获取当前时间,与上一次执行函数的时间差是否达到指定的时间间隔,从而控制函数的执行频率,实现节流。
20. 简单的深拷贝
const deepClone = (obj) => {
const clonedObj = JSON.parse(JSON.stringify(obj));
console.log(clonedObj);
return clonedObj;
};
const obj = { a: 1, b: { c: 2 } };
deepClone(obj); // { a: 1, b: { c: 2 } }
使用JSON对象的parse()和stringify()方法,将对象转换为字符串,再将字符串转换为对象,从而实现简单的深拷贝。
21. 使用Promise封装XMLHttpRequest
const request = (method, url, data) =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = () => {
reject(new Error('Network Error'));
};
xhr.send(data);
});
request('GET', '<https://jsonplaceholder.typicode.com/posts/1>').then((response) => console.log(response));
使用Promise对象封装XMLHttpRequest,实现异步请求。