Lodash profile
Lodash is a consistent, modular, high-performance JavaScript utility library.
Lodash is distributed under the MIT Open Source license and supports the latest operating environment. Look at the differences between component versions and choose one that works for you.
This note is a common way to document, some of which can be done via ES6, and some of which are not important, are skipped and filtered for personal use.
Tuimao233.gigie. IO/MAO-blog /no…
The installation
Browser environment:
<script src="lodash.js"></script>
Copy the code
Through the NPM:
$ npm i -g npm
$ npm i --save lodash
Copy the code
Node. Js:
// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
// Load the FP build for immutable auto-curried iteratee-first data-last methods.
var fp = require('lodash/fp');
// Load method categories.
var array = require('lodash/array');
var object = require('lodash/fp/object');
// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
var at = require('lodash/at');
var curryN = require('lodash/fp/curryN');
Copy the code
Why Lodash?
Lodash makes JavaScript easier by making it easier to use arrays, Numbers, objects, Strings, and so on. Lodash’s modular approach is ideal for:
- Traverses array, Object, and String
- Manipulate and test values
- Create functions that conform to functionality
Supplementary tools
- Futil-js is a set of utilities that complement LoDash.
Array class method
Array splitting (Chunk)
Divide an array into blocks of size and form these blocks into a new array. If the array cannot be split into all equal length blocks, the last remaining elements form a block.
_.chunk(['a'.'b'.'c'.'d'].2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a'.'b'.'c'.'d'].3);
// => [['a', 'b', 'c'], ['d']]
Copy the code
Filtering non-true (COMPACT)
Creates a new array containing all the non-false value elements in the original array. Examples of false, null,0, “”, undefined, and NaN are all considered “false values”.
_.compact([0.1.false.2.' '.3]);
// => [1, 2, 3]
Copy the code
Value and Array linking (concat)
Create a new array and concatenate array with any array or value.
var array = [1];
var other = _.concat(array, 2[3], [[4]]);
console.log(other);
// => [1, 2, 3, [4]]
console.log(array);
/ / = > [1]
Copy the code
Filter array values (difference)
Creates an array with unique array values that are not included in any other given array.
_.difference([3.2.1], [4.2]);
/ / = > [3, 1)
Copy the code
The receiver takes an iteratee and calls each element in array and values to compare the resulting values.
_.differenceBy([3.1.2.2.1.3], [4.4.2.5].Math.floor);
/ / = > [3.1, 1.3]
// The `_.property` iteratee shorthand.
_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1}].'x');
// => [{ 'x': 2 }]
Copy the code
Accepts a comparator that calls to compare elements in array and values. The resulting value is selected from the first array.
var objects = [{ 'x': 1.'y': 2 }, { 'x': 2.'y': 1 }];
_.differenceWith(objects, [{ 'x': 1.'y': 2 }], _.isEqual);
// => [{ 'x': 2, 'y': 1 }]
Copy the code
Array slice (drop)
Create a sliced array, removing the n elements before array. (n Default value: 1.)
_.drop([1.2.3]);
/ / = > [2, 3]
_.drop([1.2.3].2);
/ / = > [3]
_.drop([1.2.3].5);
/ / = > []
_.drop([1.2.3].0);
// => [1, 2, 3]
Copy the code
Create a sliced array that removes n elements from the end of the array. (n Default value: 1.)
_.dropRight([1.2.3]);
/ / = > [1, 2]
_.dropRight([1.2.3].2);
/ / = > [1]
_.dropRight([1.2.3].5);
/ / = > []
_.dropRight([1.2.3].0);
// => [1, 2, 3]
Copy the code
Array fill
An array is populated (replaced) with a value, starting at the start position and ending at the end position (but excluding the end position).
var array = [1.2.3];
_.fill(array, 'a');
console.log(array);
// => ['a', 'a', 'a']
Copy the code
Alternative method (array.fill)
var array = [1.2.3].fill('a')
console.log(array);
// => ['a', 'a', 'a']
Copy the code
Array Dimension reduction (Flatten)
Reduces the nesting depth of an array by one level.
_.flatten([1[2[3[4]], 5]]);
// => [1, 2, [3, [4]], 5]
Copy the code
Recurse an array to a one-dimensional array.
_.flattenDeep([1[2[3[4]], 5]]);
// => [1, 2, 3, 4, 5]
Copy the code
Reduce the nesting level of an array recursively based on depth
var array = [1[2[3[4]], 5]];
_.flattenDepth(array, 1);
// => [1, 2, [3, [4]], 5]
_.flattenDepth(array, 2);
// => [1, 2, 3, [4], 5]
Copy the code
Alternative (flat or flatMap)
// flat: converts a multidimensional array to a lower-dimensional array
const arr = [1.2.3.4[5.6[7.8.9]]]
// The conversion depth is a number
console.log(arr.flat(2))
// flatMap: If traversal returns a multidimensional array, convert to a lower-dimensional array
const arr = [1.2.3.4]
const result = arr.flatMap(item= > [item*10])
Copy the code
Converting two-dimensional arrays to objects (fromPairs)
Returns an object made of pairs of keys based on a two-dimensional array.
_.fromPairs([['fred'.30], ['barney'.40]]);
// => { 'fred': 30, 'barney': 40 }
Copy the code
Alternatives (Object.fromentries)
const result = Object.fromEntries([
['name'.Silicon Valley],
['xueke'.'Java, Big Data, front-end, Cloud Computing ']])console.log(result) // 0> {xueke :xueke, xueke :xueke, xueke :xueke, xueke :xueke... }
const m = new Map()
m.set('name'.'ATGUIGU')
const result2 = Object.fromEntries(m)
console.log(result2) // -> name:ATGUIGU
// Object.entries (ES8)
const arr = Object.entries({
name: Silicon Valley
})
console.log(arr)
Copy the code
Intersection Compares unique arrays for equality.
Creates an array of unique values that contain elements in all the given arrays, using SameValueZero for equality comparisons. (Note: can be understood as the intersection of a given array)
_.intersection([2.1], [4.2], [1.2]);
/ / = > [2]
Copy the code
Remove the specified element value (pull)
Removes all elements in the array that are equal to the given value and uses SameValueZero for an congruent comparison.
var array = [1.2.3.1.2.3];
_.pull(array, 2.3);
console.log(array);
/ / = > [1, 1)
Copy the code
This method is similar to _. Pull except that it receives an array of values to remove.
var array = [1.2.3.1.2.3];
_.pullAll(array, [2.3]);
console.log(array);
/ / = > [1, 1)
Copy the code
Remove elements by index (pullAt)
Removes the corresponding element from the array based on the indexes and returns an array of removed elements.
var array = [5.10.15.20];
var evens = _.pullAt(array, 1.3);
console.log(array);
/ / = > [5, 15]
console.log(evens);
/ / = > [10, 20]
Copy the code
Alternative (array.splice)
Sort and de-duplicate (sortedUniq)
This method is similar to _. Uniq except that it optimizes sorting arrays.
_.sortedUniq([1.1.2]);
/ / = > [1, 2]
Copy the code
Array de-duplication (UNIQ)
Create a deduplicated array copy. SameValueZero was used for equivalence comparison. Only elements that appear for the first time are retained.
_.uniq([2.1.2]);
/ / = > [2, 1)
Copy the code
Collection class method
Check if every is true
Predicate checks whether all elements in a collection return a true value. As soon as the predicate returns false values, the iteration stops. Predicate (assertion functions) call three parameters: (the value of the index, | key collection).
_.every([true.1.null.'yes'].Boolean);
// => false
var users = [
{ 'user': 'barney'.'age': 36.'active': false },
{ 'user': 'fred'.'age': 40.'active': false}];// The `_.matches` iteratee shorthand.
_.every(users, { 'user': 'barney'.'active': false });
// => false
// The `_.matchesProperty` iteratee shorthand.
_.every(users, ['active'.false]);
// => true
// The `_.property` iteratee shorthand.
_.every(users, 'active');
// => false
Copy the code
Filter set
var users = [
{ 'user': 'barney'.'age': 36.'active': true },
{ 'user': 'fred'.'age': 40.'active': false}]; _.filter(users,function(o) { return! o.active; });// => objects for ['fred']
Copy the code
Traversal set (forEach)
_ ([1.2]).forEach(function(value) {
console.log(value);
});
// => Logs `1` then `2`.
_.forEach({ 'a': 1.'b': 2 }, function(value, key) {
console.log(key);
});
// => Logs 'a' then 'b' (iteration order is not guaranteed).
Copy the code
Check whether elements exist (includes)
Check if the value is in the collection. If collection is a string, then check if value is in the string, otherwise use SameValueZero for equivalence comparison. If fromIndex is specified to be negative, the retrieval starts at the end of the collection.
_.includes([1.2.3].1);
// => true
_.includes([1.2.3].1.2);
// => false
_.includes({ 'user': 'fred'.'age': 40 }, 'fred');
// => true
_.includes('pebbles'.'eb');
// => true
Copy the code
Traverse and return the map
Create an array where value is the result returned by iteratee after iterating through each element in the collection. Iteratee called iterative function, three parameters: (value, the index | key, collection).
function square(n) {
return n * n;
}
_.map([4.8], square);
/ / = > [16, 64]
_.map({ 'a': 4.'b': 8 }, square);
// => [16, 64] (iteration order is not guaranteed)
var users = [
{ 'user': 'barney' },
{ 'user': 'fred'}];// The `_.property` iteratee shorthand.
_.map(users, 'user');
// => ['barney', 'fred']
Copy the code
Traverse and return statistics (reduce)
Compressing the collection to a value iteratee iteratee through each element of the collection, each value returned as the first argument to iteratee for the next iteration. If no accumulator is provided, the first element in the Collection is the initial value. (Note: The accumulator parameter is used as the first parameter of iteratee during the first iteration.) Iteratee call four parameters: (accumulator, the value, the index | key, collection).
_.reduce([1.2].function(sum, n) {
return sum + n;
}, 0);
/ / = > 3
_.reduce({ 'a': 1.'b': 2.'c': 1 }, function(result, value, key) {
(result[value] || (result[value] = [])).push(key);
return result;
}, {});
// => {'1': ['a', 'c'], '2': ['b']}
Copy the code
Return random element value (sample)
Get a random element from the collection.
_.sample([1.2.3.4]);
/ / = > 2
Copy the code
Shuffle elements
Create a collection of scrambled values. Use the Fisher-Yates Shuffle version.
_.shuffle([1.2.3.4]);
// => [4, 1, 3, 2]
Copy the code
Return the collection length (size)
Returns the length of a collection, or if the collection is an array or string. If the collection is an object, returns the number of its enumerable properties.
_.size([1.2.3]);
/ / = > 3
_.size({ 'a': 1.'b': 2 });
/ / = > 2
_.size('pebbles');
/ / = > 7
Copy the code
Function class method
Qualified: call after n times (after)
_. Reverse function of before; This method creates a function that fires func when it is called n or more times.
var saves = ['profile'.'settings'];
var done = _.after(saves.length, function() {
console.log('done saving! ');
});
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
Copy the code
Restricted parameter (ARY)
Create a function that calls func. A call to func takes a maximum of n arguments and ignores the extra arguments.
_.map(['6'.'8'.'10'], _.ary(parseInt.1));
// => [6, 8, 10]
Copy the code
Limit: no call after n times (before)
Create a function that calls func not more than n times, using the this binding and the arguments to create the function. A subsequent call to this function returns the result of the last call to func.
jQuery(element).on('click', _.before(5, addContactToList));
// => A maximum of four contacts can be added to the list
Copy the code
The number of arguments returns a result or function (curry)
Creates a function that takes arguments to func, either calls the result returned by func, or returns the result executed by func if the required arguments are already provided. Or return a function that takes the remaining func arguments. You can use func. Length to force the number of arguments to be accumulated.
var abc = function(a, b, c) {
return [a, b, c];
};
var curried = _.curry(abc);
curried(1) (2) (3);
// => [1, 2, 3]
curried(1.2) (3);
// => [1, 2, 3]
curried(1.2.3);
// => [1, 2, 3]
// Curried with placeholders.
curried(1) (_,3) (2);
// => [1, 2, 3]
Copy the code
Anti-jitter function (Debounce)
Create a Debmentioning function, which will call the func method after the last call with a wait of milliseconds. The debmentioning function provides a cancel method to cancel the delayed function call and flush method to be called immediately. Can provide a options (option) object to decide how to call func method, the options. The leading and | or options. How to trigger the before and after the trailing decided to delay (note: after the first call waiting or waiting for the call). The func call will pass in the last parameter to the debmentioning function. The next call debmentioning function will return the result of the last func call.
// Avoid expensive computation overhead when the window changes.
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
// When clicked, 'sendMail' is then called.
jQuery(element).on('click', _.debounce(sendMail, 300, {
'leading': true.'trailing': false
}));
// Make sure that 'batchLog' fires within 1 second after the first call.
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// Cancel a trailing anti-shake call
jQuery(window).on('popstate', debounced.cancel);
Copy the code
Qualified: After the stack clears (defer)
Postpone calling func until the current stack is cleared. When called, any additional arguments are passed to func.
_.defer(function(text) {
console.log(text);
}, 'deferred');
// => some output 'deferred' for a millisecond or longer.
Copy the code
Memoize Returned contents
Create a function that caches func results. If resolver is provided, the return value of the resolver is used as the result of the key cache function. By default, the first parameter is used as the cache key. This is bound to the cache function when func is called.
var object = { 'a': 1.'b': 2 };
var other = { 'c': 3.'d': 4 };
var values = _.memoize(_.values);
values(object);
/ / = > [1, 2]
values(other);
/ / = > [3, 4]
object.a = 2;
values(object);
/ / = > [1, 2]
// Modify the result cache.
values.cache.set(object, ['a'.'b']);
values(object);
// => ['a', 'b']
// Replace '_.memoize.cache'.
_.memoize.Cache = WeakMap;
Copy the code
The result of the function is negate.
Create a function that inverts the result of the assertion function func. When the func asserts function is called, this is bound to the created function and is passed the corresponding argument.
function isEven(n) {
return n % 2= =0;
}
_.filter([1.2.3.4.5.6], _.negate(isEven));
// => [1, 3, 5]
Copy the code
Call only once (once)
Create a function that can only call func once. Repeated calls return the result of the first call. When func is called, this is bound to the created function and is passed the corresponding argument.
var initialize = _.once(createApplication);
initialize();
initialize();
// initialize can only call createApplication once.
Copy the code
Frequency throttle
Create a throttling function that executes func at most once in wait seconds. This function provides a cancel method to cancel the delayed function call and a flush method to call immediately. Can provide an options object to decide how to call func method, the options. The leading and | or options. How to trigger the before and after the trailing decided to wait. Func passes the last argument to the function. The subsequent function call returns the result of the last func call.
// Avoid overly updated positioning while scrolling
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
// Invoke 'renewToken' after clicking, but more than once within 5 minutes.
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
// Cancel a trailing throttling call.
jQuery(window).on('popstate', throttled.cancel);
Copy the code
Language class method
CastArray (castArray)
If value is not an array, it is forced to be an array.
_.castArray(1);
/ / = > [1]
_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]
_.castArray('abc');
// => ['abc']
_.castArray(null);
// => [null]
_.castArray(undefined);
// => [undefined]
_.castArray();
/ / = > []
var array = [1.2.3];
console.log(_.castArray(array) === array);
// => true
Copy the code
Numerical shallow copy (Clone)
Create a shallow copy of value.
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
Copy the code
Numerical deep copy
This method is similar to _.clone except that it copies the value recursively. (Also called deep copy).
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
Copy the code
Assertion detection value (conformsTo)
var object = { 'a': 1.'b': 2 };
_.conformsTo(object, { 'b': function(n) { return n > 1; }});// => true
_.conformsTo(object, { 'b': function(n) { return n > 2; }});// => false
Copy the code
Numerical detection (IS [type])
Check whether value is an Array object.
_.isArray([1.2.3]);
// => true
Copy the code
Check whether the value is an ArrayBuffer object.
_.isArrayBuffer(new ArrayBuffer(2));
// => true
Copy the code
Check if value is a primitive Boolean type or object.
_.isBoolean(false);
// => true
Copy the code
Check if value is a buffer.
_.isBuffer(new Buffer(2));
// => true
Copy the code
Check whether value is a Date object.
_.isDate(new Date);
// => true
Copy the code
Check if value can be a DOM element.
_.isElement(document.body);
// => true
Copy the code
Check if value is a Function object.
_.isFunction(_);
// => true
Copy the code
Check whether value is an integer.
_.isInteger(3);
// => true
Copy the code
Check whether value is a NaN.
Note: This method is based on number. isNaN, which differs from global isNaN in that global isNaN returns true for undefined and other non-numeric values.
_.isNaN(NaN);
// => true
Copy the code
Check whether value is null or undefined.
_.isNil(null);
// => true
Copy the code
Check whether valuealue is null.
_.isNull(null);
// => true
Copy the code
Check whether the value is a primitive Number or an object.
_.isNumber(3);
// => true
Copy the code
Check whether value is a RegExp object.
_.isRegExp(/abc/);
// => true
Copy the code
Deep comparison value equality (isEqual)
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
Copy the code
Mathematical method
Round up (CeiL)
Round up the number based on precision. (Note: Precision can be understood as preserving a few decimal places.)
_.ceil(4.006);
/ / = > 5
_.ceil(6.004.2);
/ / = > 6.01
_.ceil(6040, -2);
/ / = > 6100
Copy the code
Round down (floor)
Round down the number based on precision. (Note: Precision can be understood as preserving a few decimal places.)
_.floor(4.006);
/ / = > 4
_.floor(0.046.2);
/ / = > 0.04
_.floor(4060, -2);
/ / = > 4000
Copy the code
Array maximum value (Max)
Calculates the maximum value in an array. Returns undefined if array is empty or false.
_.max([4.2.8.6]);
/ / = > 8
_.max([]);
// => undefined
Copy the code
Array average (mean)
Calculates the average of the array.
_.mean([4.2.8.6]);
/ / = > 5
Copy the code
Array minimum (min)
Calculates the minimum value in the array. Returns undefined if array is empty or false.
_.min([4.2.8.6]);
/ / = > 2
_.min([]);
// => undefined
Copy the code
Round (round)
_.round(4.006);
/ / = > 4
_.round(4.006.2);
/ / = > 4.01
_.round(4060, -2);
/ / = > 4100
Copy the code
Total array value (sum)
_.sum([4.2.8.6]);
/ / = > 20
Copy the code
Number class method
Clamp
Returns a value limited between lower and upper.
_.clamp(-10, -5.5);
/ / = > - 5
_.clamp(10, -5.5);
/ / = > 5
Copy the code
Random interval value
Produces a number between lower and upper. Returns a number between 0 and the supplied number if only one argument is provided. If floating is set to true, or lower or upper is a float, the result returns a float.
_.random(0.5);
// => an integer between 0 and 5
_.random(5);
// => also an integer between 0 and 5
_.random(5.true);
// => a floating-point number between 0 and 5
_.random(1.2.5.2);
// => a floating-point number between 1.2 and 5.2
Copy the code
Object class method
Take the path value as array (at)
Create an array of values from the corresponding values of the Paths path of Object.
var object = { 'a': [{ 'b': { 'c': 3}},4]}; _.at(object, ['a[0].b.c'.'a[1]']);
/ / = > [3, 4]
Copy the code
Assign and merge (defaults)
_.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
// => { 'a': 1, 'b': 2 }
_.defaultsDeep({ 'a': { 'b': 2}}, {'a': { 'b': 1.'c': 3}});// => { 'a': { 'b': 2, 'c': 3 } }
Copy the code
Traversal object (forIn)
Iteratee is used to traverse the object’s own and inherited enumerable properties. Iteratee takes three arguments: value, key, and object. If false is returned, iteratee will exit the loop prematurely.
function Foo() {
this.a = 1;
this.b = 2;
}
Foo.prototype.c = 3;
_.forIn(new Foo, function(value, key) {
console.log(key);
});
// Logs 'a', 'b', then 'c'.
Copy the code
Get path value (get)
Gets the value based on the path of the object. If the parse value is undefined, it will be replaced by defaultValue.
var object = { 'a': [{ 'b': { 'c': 3}}}; _.get(object,'a[0].b.c');
/ / = > 3
_.get(object, ['a'.'0'.'b'.'c']);
/ / = > 3
_.get(object, 'a.b.c'.'default');
// => 'default'
Copy the code
Is there a path (has)
Check whether path is a direct property of object.
var object = { 'a': { 'b': 2}};var other = _.create({ 'a': _.create({ 'b': 2})}); _.has(object,'a');
// => true
_.has(object, 'a.b');
// => true
_.has(object, ['a'.'b']);
// => true
_.has(other, 'a');
// => false
Copy the code
Remove path (unset)
Remove an attribute from the path of object.
var object = { 'a': [{ 'b': { 'c': 7}}}; _.unset(object,'a[0].b.c');
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
_.unset(object, ['a'.'0'.'b'.'c']);
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
Copy the code
String class method
CamelCase conversion
Converts the string string to hump.
_.camelCase('Foo Bar');
// => 'fooBar'
_.camelCase('--foo-bar--');
// => 'fooBar'
_.camelCase('__FOO_BAR__');
// => 'fooBar'
Copy the code
Capitalize
Converts the string string to uppercase and the rest to lowercase.
_.capitalize('FRED');
// => 'Fred'
Copy the code
Detecting tail characters (endsWith)
Checks whether the string string ends with the given target string.
_.endsWith('abc'.'c');
// => true
_.endsWith('abc'.'b');
// => false
_.endsWith('abc'.'b'.2);
// => true
Copy the code
Underline in conversion (kebabCase)
Convert the string string to kebab case.
_.kebabCase('Foo Bar');
// => 'foo-bar'
_.kebabCase('fooBar');
// => 'foo-bar'
_.kebabCase('__FOO_BAR__');
// => 'foo-bar'
Copy the code
Convert Spaces to separate (lowerCase)
The conversion string string separates words with Spaces and converts them to lowercase.
_.lowerCase('--Foo-Bar--');
// => 'foo bar'
_.lowerCase('fooBar');
// => 'foo bar'
_.lowerCase('__FOO_BAR__');
// => 'foo bar'
Copy the code
Convert underline to separate (snakeCase)
_.snakeCase('Foo Bar');
// => 'foo_bar'
_.snakeCase('fooBar');
// => 'foo_bar'
_.snakeCase('--FOO-BAR--');
// => 'foo_bar'
Copy the code
lowerFirst
Converts the first letter of the string string to lowercase.
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
Copy the code
Less than length fills left and right (pad)
If the string length is less than length, the characters are padded from the left and right. If it cannot be evenly distributed, the excess length is truncated.
_.pad('abc'.8);
// => ' abc '
_.pad('abc'.8.'_ -);
// => '_-abc_-_'
_.pad('abc'.3);
// => 'abc'
_.padEnd('abc'.6);
// => 'abc '
_.padStart('abc'.6);
// => ' abc'
Copy the code
Repeat string N times (repeat)
_.repeat(The '*'.3);
/ / = > '* * *'
_.repeat('abc'.2);
// => 'abcabc'
_.repeat('abc'.0);
/ / = > '
Copy the code
Precompiled templates
Interpolate creates a precompiled template method that interpolates data in a template at the position of the “interpolate” separator. The HTML is converted to the entity in the “escape” delimiter. Allow JavaScript code to execute in the “evaluate” delimiter. Variables are freely accessible in the template. If an option object is set, the value of _. TemplateSettings is overriding.
// Interpolate creates a build template using the "interpolate" separator
var compiled = _.template('hello <%= user %>! ');
compiled({ 'user': 'fred' });
// => 'hello fred! '
// Use HTML "escape" to escape the value of data
var compiled = _.template('<b><%- value %></b>');
compiled({ 'value': '<script>' });
// => '<b><script></b>'
Execute JavaScript and generate HTML code using the "evaluate" delimiter
var compiled = _.template('<% _.forEach(users, function(user) { %><%- user %> <% }); % > ');
compiled({ 'users': ['fred'.'barney']});// => '<li>fred</li><li>barney</li>'
Use the internal 'print' function in the 'evaluate' delimiter
var compiled = _.template('<% print("hello " + user); % >! ');
compiled({ 'user': 'barney' });
// => 'hello barney! '
// Use ES delimiter instead of the default "interpolate" delimiter
var compiled = _.template('hello ${ user }! ');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles! '
// Use custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?) }}/g;
var compiled = _.template('hello {{ user }}! ');
compiled({ 'user': 'mustache' });
// => 'hello mustache! '
// Use the backslash symbol for plain text processing
var compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ 'value': 'ignored' });
// => '<%- value %>'
// Use the 'imports' option to import' jq 'as an alias for' jQuery '
var text = '<% jq.each(users, function(user) { %><%- user %> <% }); % > ';
var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
compiled({ 'users': ['fred'.'barney']});// => '<li>fred</li><li>barney</li>'
// use the 'sourceURL' option to specify the template's sourceURL
var compiled = _.template('hello <%= user %>! ', { 'sourceURL': '/basic/greeting.jst' });
compiled(data);
// => Find "greeting. JST "in the Sources TAB or Resources panel of the development tool
// Use the 'variable' option to ensure that variables are not declared in the compiled template
var compiled = _.template('hi <%= data.user %>! ', { 'variable': 'data' });
compiled.source;
// => function(data) {
// var __t, __p = '';
// __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '! ';
// return __p;
// }
// Use the 'source' feature to compile templates inline
// To view the line number, error message, stack
fs.writeFileSync(path.join(cwd, 'jst.js'), '\ var JST = {\ "main": ' + _.template(mainText).source + '\}; \ ');
Copy the code
Truncate string with suffix (truncate)
Truncate string if the string exceeds the specified maximum value. Where there’s no shortage of truncated strings, there’s no shortage of truncated strings, where there’s no shortage of truncated strings. .
_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo... '
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24.'separator': ' '
});
// => 'hi-diddly-ho there,... '
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24.'separator': /,? +/
});
// => 'hi-diddly-ho there... '
_.truncate('hi-diddly-ho there, neighborino', {
'omission': '[...]. '
});
// => 'hi-diddly-ho there, neig [...] '
Copy the code
Split words into arrays (words)
Split the words in the string into arrays.
_.words('fred, barney, & pebbles');
// => ['fred', 'barney', 'pebbles']
_.words('fred, barney, & pebbles'./[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']
Copy the code