Understand the common functions of the Lodash framework
Lodash is a popular JavaScript tool library that provides many practical functions that can simplify the development process and improve the readability and maintenance of code.This article will introduce some common functions in the Lodash framework and provide the corresponding Java code example.
1. Array function:
-__.chunk (Array, SIZE): The array is split into multiple new array according to the specified size.
List<Integer> array = Arrays.asList(1, 2, 3, 4, 5, 6);
List<List<Integer>> chunks = _.chunk(array, 3);
// chunks: [[1, 2, 3], [4, 5, 6]]
-__.filter (Array, Predicate): Filter the elements in the array according to the specified condition, and return a new array that meets conditions.
List<Integer> array = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> filtered = _.filter(array, n -> n % 2 == 0);
// filtered: [2, 4, 6]
-_ _.Map (Array, Iteratee): Execute the specified function of each element in the array and return the new array after processing.
List<Integer> array = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> mapped = _.map(array, n -> n * 2);
// mapped: [2, 4, 6, 8, 10, 12]
2. Object function:
-__.clone (obj): a clone object, returns the same copy as the original object.
Map<String, Integer> obj = new HashMap<>();
obj.put("a", 1);
Map<String, Integer> clonedObj = _.clone(obj);
-_ _.keys (obj): Returns the array of all attribute names of the given object.
Map<String, Integer> obj = new HashMap<>();
obj.put("a", 1);
obj.put("b", 2);
List<String> keys = _.keys(obj);
// keys: ["a", "b"]
-_ _.Values (obj): Returns the array of all attribute values of the given object.
Map<String, Integer> obj = new HashMap<>();
obj.put("a", 1);
obj.put("b", 2);
List<Integer> values = _.values(obj);
// values: [1, 2]
3. String function:
-_ _.startswith (str, target): Determine whether the strings start with the specified target string.
String str = "Hello World";
boolean startsWith = _.startsWith(str, "Hello");
// startsWith: true
-_ _.endswith (str, target): Determine whether the strings end to end with a specified target string.
String str = "Hello World";
boolean endsWith = _.endsWith(str, "World");
// endsWith: true
-__.trim (STR): Remove the space at both ends of the string.
String str = " Hello World ";
String trimmed = _.trim(str);
// trimmed: "Hello World"
The above is simply a brief introduction to some common functions in the Lodash framework, and there are other rich functions for developers.Mastering Lodash can greatly improve the efficiency and quality of JavaScript development.