简介
Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。
安装
npm install lodash
常用方法
intersection 交集
_.intersection([2, 1], [4, 2], [1, 2]); // => [2]
_.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); // => [2.1]
_.intersectionBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
[
{ name: "product1", price: 100 },
{ name: "product3", price: 300 },
],
"name"
); // [{ name: "product1", price: 100 }]
union 并集
_.union([2], [1, 2]); // => [2, 1]
_.unionBy([2.1], [1.2, 2.3], Math.floor); // => [2.1, 1.2]
_.unionBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
[
{ name: "product1", price: 100 },
{ name: "product3", price: 300 },
],
"name"
); // [{ name: "product1", price: 100 }, { name: "product2", price: 200 }, { name: "product3", price: 300 }]
difference 排除
_.difference([2, 1], [2, 3]); // => [1]
__.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // => [1.2]
_.differenceBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
[
{ name: "product1", price: 100 },
{ name: "product3", price: 300 },
],
"name"
); // [{ name: "product2", price: 200 }]
sum 总和
_.sum([4, 2]); // => 6
_sumBy([6.6, 2.8], Math.floor); // => 8
_.sumBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
"price"
); // 300
mean 平均值
_.mean([4, 2]); // => 3
_.meanBy([4.2, 2.1], Math.floor); // => 3
_.meanBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
"price"
); // 150
maxBy 最大值
_.maxBy([4, 2], Math.floor); // => 4
_.maxBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
"price"
); // { name: "product2", price: 200 }
min 最小值
_.min([4, 2]); // => 2
_.minBy([4.2, 2.1], Math.floor); // => 2
_.minBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
"price"
); // { name: "product1", price: 100 }
sortBy 排序
_.sortBy([2.1, 1.2], Math.floor); // => [1.2, 2.1]
_.sortBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
"price" // => [{ name: "product1", price: 100 }, { name: "product2", price: 200 }]
);
chunk 分块
_.chunk(["a", "b", "c", "d"], 2); // => [['a', 'b'], ['c', 'd']]
clone 浅拷贝
const obj = {
x: 3,
y: 4,
};
const shallow = _.clone(obj); // => { x: 3, y: 4 }
console.log(shallow.x === obj.x); // => true
cloneDeep 深拷贝
const obj = {
x: 3,
y: 4,
};
const deep = _.cloneDeep(obj); // => { x: 3, y: 4 }
console.log(deep.x === obj.x); // => false
去重
_.uniq([2, 1, 2]); // => [2, 1]
_.uniqBy([2.1, 1.2, 2.3], Math.floor); // => [2.1, 1.2]
_.uniqBy(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
{ name: "product1", price: 100 },
],
"name"
); // [{ name: "product1", price: 100 }, { name: "product2", price: 200 }]
去空
_.compact([0, 1, false, 2, "", 3]); // => [1, 2, 3]
find 查找
_.find([1, 2, 3, 4], (n) => n % 2 == 0); // => 2
_.find(
[
{ name: "product1", price: 100 },
{ name: "product2", price: 200 },
],
{ price: 200 }
); // => { name: "product2", price: 200 }
debounce 防抖
_.debounce(function () {
console.log("debounce");
}, 1000);
throttle 节流
_.throttle(function () {
console.log("throttle");
}, 1000);
经典场景
防抖
import React, { useState, useCallback } from "react";
import _ from "lodash";
export default function LodashDemo() {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const [isSearching, setIsSearching] = useState(false);
// 模拟搜索API调用
const mockSearch = async (term) => {
setIsSearching(true);
// 模拟网络延迟
await new Promise((resolve) => setTimeout(resolve, 500));
const results = [
`Result for: ${term} 1`,
`Result for: ${term} 2`,
`Result for: ${term} 3`,
];
setSearchResults(results);
setIsSearching(false);
};
// 使用 useCallback 和 debounce 创建防抖搜索函数
const debouncedSearch = useCallback(
_.debounce((term) => {
if (term.trim()) {
mockSearch(term);
} else {
setSearchResults([]);
}
}, 500),
[]
);
// 处理输入变化
const handleInputChange = (e) => {
const value = e.target.value;
setSearchTerm(value);
debouncedSearch(value);
};
return (
<div className="min-h-screen bg-zinc-900 text-white p-8">
<div className="max-w-2xl mx-auto">
<h1 className="text-3xl font-bold mb-8 text-center">
Search with Debounce
</h1>
<div className="bg-zinc-800 rounded-xl p-6 shadow-2xl">
<div className="relative">
<input
type="text"
value={searchTerm}
onChange={handleInputChange}
placeholder="Type to search..."
className="w-full px-4 py-3 bg-zinc-700 rounded-lg text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{isSearching && (
<div className="absolute right-3 top-3">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white"></div>
</div>
)}
</div>
<div className="mt-4">
<h2 className="text-xl font-semibold mb-2">Search Results:</h2>
{searchResults.length > 0 ? (
<ul className="space-y-2">
{searchResults.map((result, index) => (
<li
key={index}
className="bg-zinc-700 p-3 rounded-lg hover:bg-zinc-600 transition-colors"
>
{result}
</li>
))}
</ul>
) : (
<p className="text-zinc-400">
{searchTerm ? "No results found" : "Start typing to search..."}
</p>
)}
</div>
</div>
</div>
</div>
);
}
节流
import React, { useState, useEffect, useCallback } from "react";
import _ from "lodash";
export default function LodashDemo() {
const [scrollPosition, setScrollPosition] = useState(0);
const [scrollCount, setScrollCount] = useState(0);
const [throttleCount, setThrottleCount] = useState(0);
const [isThrottled, setIsThrottled] = useState(false);
// 使用 useCallback 和 throttle 创建节流滚动处理函数
const throttledScrollHandler = useCallback(
_.throttle(() => {
setThrottleCount((prev) => prev + 1);
setIsThrottled(true);
setTimeout(() => setIsThrottled(false), 1000); // 显示节流状态1秒
}, 1000),
[]
);
// 处理滚动事件
const handleScroll = useCallback(() => {
setScrollPosition(window.scrollY);
setScrollCount((prev) => prev + 1);
throttledScrollHandler();
}, [throttledScrollHandler]);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
throttledScrollHandler.cancel(); // 清理节流函数
};
}, [handleScroll, throttledScrollHandler]);
return (
<div className="min-h-[200vh] text-white">
<div className="fixed top-0 left-0 right-0 p-4 z-50">
<div className="max-w-4xl mx-auto">
<h1 className="text-2xl font-bold mb-4">
Scroll Event with Throttle
</h1>
<div className="grid grid-cols-2 gap-4">
<div className="bg-zinc-700 p-4 rounded-lg">
<h2 className="text-lg font-semibold mb-2">Scroll Statistics</h2>
<div className="space-y-2">
<p>Scroll Position: {Math.round(scrollPosition)}px</p>
<p>Total Scroll Events: {scrollCount}</p>
<p>Throttled Events: {throttleCount}</p>
<p className="text-sm text-zinc-400">
(Throttle delay: 1000ms)
</p>
</div>
</div>
<div className="bg-zinc-700 p-4 rounded-lg">
<h2 className="text-lg font-semibold mb-2">Throttle Status</h2>
<div className="space-y-2">
<div className="flex items-center space-x-2">
<div
className={`w-3 h-3 rounded-full ${
isThrottled ? "bg-green-500" : "bg-red-500"
}`}
></div>
<span>{isThrottled ? "Throttled" : "Not Throttled"}</span>
</div>
<p className="text-sm text-zinc-400">
{isThrottled
? "Scroll events are being throttled"
: "Scroll events are being processed normally"}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
原文链接:https://code.ifrontend.net/archives/358,转载请注明出处。
评论0