How can I join an array of numbers into 1 concatenated number?

前端 未结 7 1580
梦谈多话
梦谈多话 2020-12-10 12:27

How do I join this array to give me expected output in as few steps as possible?

var x = [31,31,3,1]
//expected output: x = 313131;
相关标签:
7条回答
  • 2020-12-10 12:37

    Your question asks for a number, most of the answers above are going to give you a string. You want something like this.

    const number = Number([31,31,3,1].join(""));

    0 讨论(0)
  • 2020-12-10 12:39

    Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.

    var  x = [31,31,3,1].join("");
    
    0 讨论(0)
  • 2020-12-10 12:48

    This will work

    var x = [31,31,3,1];
    var result = x.join("");
    
    0 讨论(0)
  • 2020-12-10 12:49

    Try below.

    var x = [31,31,3,1]
    var teststring = x.join("");
    
    0 讨论(0)
  • 2020-12-10 12:52

    Try join() as follows

    var x = [31,31,3,1]
    var y = x.join('');
    alert(y);

    0 讨论(0)
  • 2020-12-10 12:53

    I can't think of anything other than

    +Function.call.apply(String.prototype.concat, x)
    

    or, if you insist

    +''.concat.apply('', x)
    

    In ES6:

    +''.concat(...x)
    

    Using reduce:

    +x.reduce((a, b) => a + b, '');
    

    Or if you prefer

    x.reduce(Function.call.bind(String.prototype.concat), '')
    

    Another idea is to manipulate the array as a string, always a good approach.

    +String.prototype.replace.call(x, /,/g, '')
    

    There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.

    0 讨论(0)
提交回复
热议问题