百科网

首页 > 生活常识 > 生活经验

生活经验

JavaScript lodash的常见用法

生活经验佚名2023-05-10

Lodash是一个JavaScript的实用工具库,提供了很多常用的函数和工具,可以帮助我们更方便地操作数据和处理逻辑。本文将详细介绍Lodash的常见用法,包括对象操作、数组操作、函数操作和其他常用操作等方面。

一、对象操作

1. _.get(object, path, [defaultValue]):获取对象中指定路径的值,如果路径不存在则返回默认值。

示例:

const user = {

name: 'John',

address: {

city: 'New York',

street: '123 Main St'

}

};

_.get(user, 'address.city'); // 'New York'

_.get(user, 'address.zip', 'N/A'); // 'N/A'

2. _.set(object, path, value):设置对象中指定路径的值。

示例:

const user = {

name: 'John',

address: {

city: 'New York',

street: '123 Main St'

}

};

_.set(user, 'address.city', 'Los Angeles');

console.log(user.address.city); // 'Los Angeles'

3. _.has(object, path):判断对象中是否存在指定路径的值。

示例:

const user = {

name: 'John',

address: {

city: 'New York',

street: '123 Main St'

}

};

_.has(user, 'address.city'); // true

_.has(user, 'address.zip'); // false

4. _.keys(object):获取对象中所有的键名。

示例:

const user = {

name: 'John',

age: 30,

address: {

city: 'New York',

street: '123 Main St'

}

};

_.keys(user); // ['name', 'age', 'address']

5. _.values(object):获取对象中所有的键值。

示例:

const user = {

name: 'John',

age: 30,

address: {

city: 'New York',

street: '123 Main St'

}

};

_.values(user); // ['John', 30, {city: 'New York', street: '123 Main St'}]

二、数组操作

1. _.chunk(array, size):将数组按照指定大小分块。

示例:

const arr = [1, 2, 3, 4, 5, 6];

_.chunk(arr, 2); // [[1, 2], [3, 4], [5, 6]]

_.chunk(arr, 3); // [[1, 2, 3], [4, 5, 6]]

2. _.compact(array):去除数组中的假值,包括false、null、0、''、undefined和NaN。

示例:

const arr = [1, 0, false, '', null, undefined, NaN];

_.compact(arr); // [1]

3. _.difference(array, [values]):返回数组中不包含在指定数组中的元素。

示例:

const arr1 = [1, 2, 3, 4, 5];

const arr2 = [2, 4, 6];

_.difference(arr1, arr2); // [1, 3, 5]

4. _.drop(array, [n=1]):返回去除数组中前n个元素后的剩余元素。

示例:

const arr = [1, 2, 3, 4, 5];

_.drop(arr); // [2, 3, 4, 5]

_.drop(arr, 2); // [3, 4, 5]

5. _.take(array, [n=1]):返回数组中前n个元素。

示例:

const arr = [1, 2, 3, 4, 5];

_.take(arr); // [1]

_.take(arr, 3); // [1, 2, 3]

三、函数操作

1. _.debounce(func, [wait=0], [options={}]):创建一个函数,该函数在指定时间间隔内只执行一次。

示例:

const debouncedFn = _.debounce(() => {

console.log('Debounced function called');

}, 1000);

debouncedFn(); // 调用后1秒才执行

2. _.throttle(func, [wait=0], [options={}]):创建一个函数,该函数在指定时间间隔内最多执行一次。

示例:

const throttledFn = _.throttle(() => {

console.log('Throttled function called');

}, 1000);

throttledFn(); // 调用后立即执行

setTimeout(() => {

throttledFn(); // 1秒后执行

}, 1000);

3. _.memoize(func, [resolver]):创建一个函数,该函数缓存计算结果,避免重复计算。

示例:

const fibonacci = _.memoize((n) => {

if (n < 2) {

return n;

}

return fibonacci(n - 1) fibonacci(n - 2);

});

console.log(fibonacci(10)); // 55

console.log(fibonacci(10)); // 直接返回缓存的结果

四、其他常用操作

1. _.clone(value):复制一个值。

示例:

const obj = {name: 'John'};

const clonedObj = _.clone(obj);

console.log(clonedObj); // {name: 'John'}

2. _.isEqual(value, other):判断两个值是否相等。

示例:

const obj1 = {name: 'John'};

const obj2 = {name: 'John'};

_.isEqual(obj1, obj2); // true

3. _.isEmpty(value):判断一个值是否为空。

示例:

_.isEmpty(null); // true

_.isEmpty(undefined); // true

_.isEmpty(''); // true

_.isEmpty([]); // true

_.isEmpty({}); // true

4. _.omit(object, [paths]):返回对象中除了指定键之外的所有键值对。

示例:

const obj = {name: 'John', age: 30, address: '123 Main St'};

_.omit(obj, ['address']); // {name: 'John', age: 30}

5. _.pick(object, [paths]):返回对象中指定键的键值对。

示例:

6. _.random([lower=0], [upper=1], [floating]):返回指定范围内的随机数。

示例:

_.random(1, 10); // 生成1到10之间的整数

_.random(1.5, 10.5, true); // 生成1.5到10.5之间的浮点数

7. _.template(string, [options={}]):编译一个模板字符串,返回一个函数,该函数可以根据传入的数据生成最终的字符串。

示例:

const compiled = _.template('Hello <%= name %>!');

console.log(compiled({name: 'John'})); // 'Hello John!'

8. _.truncate(string, [options={}]):截取字符串,如果超过指定长度,则用...代替。

示例:

const str = 'The quick brown fox jumps over the lazy dog';

_.truncate(str, {length: 20}); // 'The quick brown fox...'

_.truncate(str, {length: 20, omission: ' (...continued)'}); // 'The quick brown fox (...continued)'

9. _.uniqueId([prefix='']):生成唯一的ID。

示例:

_.uniqueId('user_'); // 'user_1'

_.uniqueId('user_'); // 'user_2'

10. _.zip([arrays]):将多个数组合并成一个数组,每个元素为原数组中相同位置的元素组成的数组。

示例:

const arr1 = [1, 2, 3];

const arr2 = ['a', 'b', 'c'];

_.zip(arr1, arr2); // [[1, 'a'], [2, 'b'], [3, 'c']]

总结

Lodash是一个非常实用的JavaScript工具库,提供了很多常用的函数和工具,可以大大提高开发效率。本文介绍了Lodash的常见用法,包括对象操作、数组操作、函数操作和其他常用操作等方面,希望对大家有所帮助。