美文网首页
数组方法实现--join

数组方法实现--join

作者: 无名白丁 | 来源:发表于2019-12-19 12:56 被阅读0次

Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.

Use Array.prototype.reduce() to combine elements into a string. Omit the second argument, separator, to use a default separator of ','. Omit the third argument, end, to use the same value as separator by default.

const join = (arr, separator = ',', end = separator) =>
  arr.reduce(
    (acc, val, i) =>
      i === arr.length - 2
        ? acc + val + end
        : i === arr.length - 1
        ? acc + val
        : acc + val + separator,
    ''
  );

EXAMPLES
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen"
join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen"
join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"

相关文章

  • js数组常用方法,看这篇就够了

    1、join()(数组转字符串) ① 数组转字符串 ② 重复字符串 通过join()方法可以实现重复字符串,只需传...

  • JS 数组常用方法

    1、join() (数组转字符串) 数组转字符串,方法只接收一个参数:即默认为逗号分隔符()。 join()实现重...

  • 数组常用方法

    数组常用方法 一、js数组常用方法: 1、join() Array.join() 方法将数组中所有元素都转换成字...

  • 数组方法实现--join

    Joins all elements of an array into a string and returns ...

  • JavaScript数组Array常用方法

    join()方法 join() 方法:用于把数组中的所有元素放入一个字符串。 join()方法将数组中的所有元素转...

  • 数组常用方法

    数组常用方法收集 1、join() --原数组不变,返回字符串 join(separator): 将数组的元素组起...

  • JS数组

    创建数组 数组方法 push(), pop() shift(), unshift() join() sort() ...

  • JS数组常用方法大全

    数组的方法有数组原型方法,也有从object对象继承来的方法,下面就介绍一下数组常用方法:join() --...

  • Array.prototype.join()方法:

    join()方法将数组(或一个类数组对象)的所有元素连接到一个字符串中。PS: join()方法,不会改变数组! ...

  • 数组扁平化的实现方式

    数组扁平化的实现方式 方法一 利用数组的 join() 转换成字符串,利用字符串的 split() 转换成...

网友评论

      本文标题:数组方法实现--join

      本文链接:https://www.haomeiwen.com/subject/ubemnctx.html