Home  >  Q&A  >  body text

javascript - How to operate array [2,4,8] so that it becomes (2 | 4 | 8)

How to operate array [2,4,8] to make it become (2 | 4 | 8)? ?

[2,4,8].join("|") == "2 | 4 | 8", which cannot reach the expected form (2 | 4 | 8).
Tried using join repeatedly ....Can't you add the outer brackets? Please help...

学习ing学习ing2561 days ago859

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-06-30 10:01:38

    join 2 times

    > ['(',')'].join([2, 4, 8].join("|"))
    '(2|4|8)'

    @vue_小白

    Now we need to convert an array [1,2,4] into a numeric type (1|2|4), because we need to convert the converted (1|2|4) into hexadecimal later... So now I don’t know how to convert the array [1,2,4] into (1|2|4).toString(16) operates like this

    The method is as follows:

    > arr = [1,2,4]
    > arr.reduce((x,y)=>x|y,0).toString(16)
    '7'

    Reply
    0
  • 大家讲道理

    大家讲道理2017-06-30 10:01:38

    "(" + [2, 4, 8].join("|") + ")"

    Reply
    0
  • 某草草

    某草草2017-06-30 10:01:38

    1. Wow, if you customize a prototype yourself, the default one cannot be achieved.

    var arr = [1, 2, 34];
    Array.prototype.FuckJoin = function (start, sp, end) {
      console.log(this);
      var res = start;
      this.forEach(function (a, index) {
        res += a.toString();
        if (arr.length - 1 > index) {
          res += sp.toString();
        }
      })
      return (res + end);
    };
    console.log(arr.FuckJoin('(', '|', ')'));
    

    2. Isn’t it enough to add a () twice to the string?

    Reply
    0
  • CancelReply