Lodash _.join() 方法
_.join()函数用于将数组中的所有元素转换为由分隔符分隔的字符串。
句法:
_.join(array, [separator=','])
参数:此方法接受上面提到的两个参数,如下所述:
- 数组:它是要执行连接操作的原始数组。
- 分隔符:分隔数组中每个元素的字符串。如果默认保留数组元素,则用逗号(,)分隔。
返回值:此函数返回通过使用分隔符连接数组的所有元素而创建的字符串。
注意:在使用下面给出的代码之前,通过使用命令 npm 安装 lodash 来安装 lodash 模块。
示例 1:在此示例中,函数join() 使用'|'将数组的元素连接成一个字符串.
Javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be joined
let array = [ 1, 2, 3, 4, 5, 6 ];
let newArray = lodash.join(array, '|');
console.log("Before Join: " + array);
// Printing newArray
console.log("After Join: " + newArray);
Javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be joined
let array = [ 1, 2, 3, 4, 5, 6 ];
let newArray = lodash.join(array);
console.log("Before Join: " + array);
// Printing newArray
console.log("After Join: " + newArray);
Javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be joined
let array = [ 1, 2, 3, 4, 5, 6 ];
let newArray = lodash.join(array,'');
console.log("Before Join: " + array);
// Printing newArray
console.log("After Join: " + newArray);
输出:
示例 2:在此示例中,函数join() 使用', '将数组的元素连接成一个字符串,因为它是默认值。
Javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be joined
let array = [ 1, 2, 3, 4, 5, 6 ];
let newArray = lodash.join(array);
console.log("Before Join: " + array);
// Printing newArray
console.log("After Join: " + newArray);
输出:
示例 3:在此示例中,函数join() 使用 ' ' (空字符串)将数组元素连接成一个字符串。
Javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be joined
let array = [ 1, 2, 3, 4, 5, 6 ];
let newArray = lodash.join(array,'');
console.log("Before Join: " + array);
// Printing newArray
console.log("After Join: " + newArray);
输出: