search

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学习ing2703 days ago960

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