JS是重中之重
总结下一些手写JS问题,这些都是高频面试题,希望对你能有所帮助。
01.数组扁平化
数组扁平化是指将一个多维数组变为一个一维数组
const arr = [1, [2, [3, [4, 5]]], 6,[7,8],9];
//方法:使用flat()
const res1 = arr.flat(Infinity);
// => [1, 2, 3, 4, 5, 6,7,8,9]
2.数组去重
const arr = [1, 1, 1,2,2,3,4,4,5,5];
//方法:用Set
const result = Array.from(new Set(arr));
// 方法:用filter
const resultS = arr => {
return arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
}
// => [1, 2, 3, 4, 5]
3.debounce(防抖)
const debounce = (func, time) => {
let timeout = null;
return function() {
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(this, arguments);
}, 1000);
}
};
4.Array.prototype.filter()
是数组的原型方法之一,用于创建一个新数组,其中包含满足指定条件的所有元素。
它接受一个回调函数作为参数,该回调函数会对数组中的每个元素进行调用,并返回一个布尔值,用于决定是否将该元素包含在新数组中。如果回调函数返回
true,则该元素会被包含在新数组中,否则会被排除。示例代码如下:
const numbers = [1, 2, 3, 4, 5];
const evenNum = numbers.filter(num => num % 2 === 0);
// evenNum为[2, 4]
5.Array.prototype.map()
用于创建一个新数组,其中包含对原数组的每个元素应用某个函数后的结果。它接受一个回调函数作为参数,该回调函数会对数组中的每个元素进行调用,并返回一个新的值,用于替换原数组中的对应元素。最后,将所有新值组成一个新数组返回。示例代码如下:
const numbers = [1, 2, 3, 4, 5];
const doubledNum = numbers.map(num => num * 2);
// doubledNum为[2, 4, 6, 8, 10]
6.Array.prototype.forEach()
用于对数组的每个元素执行指定的操作。它接受一个回调函数作为参数,该回调函数会对数组中的每个元素进行调用,但不会返回任何值。它主要用于遍历数组并执行一些副作用操作,例如修改数组元素、打印数组元素等。示例代码如下:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num);
});
//输出1, 2, 3, 4, 5
7.Array.prototype.reduce()
用于对数组中的所有元素进行累积操作,最终返回一个累积结果。它接受一个回调函数和一个初始值作为参数。回调函数会被应用到数组的每个元素上,并且接受四个参数:累积值(之前的回调函数的返回值或初始值),当前元素,当前索引和原数组。回调函数的返回值将作为下一次回调函数的累积值。最后,
reduce()方法会返回最终的累积值。示例代码如下:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// sum为15
8.Array.prototype.pop()
从数组的末尾移除最后一个元素,并返回被移除的元素。
const nums = ['1', '2', '3'];
const removedNum = nums.pop();
console.log(removedNum); // '3'
console.log(nums); // ['1', '2']
9.Array.prototype.slice()
返回一个从原数组中选定元素的新数组。原数组不会被修改
const fruits = ['apple', 'banana', 'orange', 'grape'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // ['banana', 'orange']
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']
10.Array.prototype.splice()
从数组中添加/删除元素,并返回被删除的元素组成的新数组。
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'pear', 'kiwi');
console.log(removedFruits); // ['banana', 'orange']
console.log(fruits); // ['apple', 'pear', 'kiwi', 'grape']