简体   繁体   English

如何在javascript中成对加入数组元素

[英]How to join array elements in pairs in javascript

I have a array of numbers [1,2,3,4,5,6,7,8,9,10] and I want to make it into a string like this: '1,2 3,4 5,6 7,8 9,10'. 我有一个数字数组[1,2,3,4,5,6,7,8,9,10],我想把它做成这样的字符串:'1,2 3,4 5,6 7 ,8 9,10'。 Is there some fast and simple vay to do this in javascript or do i have to use the loop? 是否有一些快速简单的方法可以在javascript中执行此操作,还是必须使用循环?

for(let i = 0; i < array.length; i++){
     if(i%2 == 0){
        res += array[i] + ',';
     } else {
        res += array[i] + ' ';
     }
}

You could get pairs with comma and then join the array with spaces for the string, but you need still a loop 您可以使用逗号对,然后将包含空格的数组加入字符串,但仍需要循环

 var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], temp = [], i = 0, string; while (i < array.length) { temp.push(array.slice(i, i += 2).join()); } string = temp.join(' '); console.log(string); 

You can use reduce to get the result you desire: 您可以使用reduce获得所需的结果:

[1,2,3,4,5,6,7,8,9,10]
    .reduce((acc, val, idx) => 
        idx % 2 === 0 
            ? (acc ? `${acc} ${val}` : `${val}`) 
            : `${acc},${val}`, '') 
// "1,2 3,4 5,6 7,8 9,10"

By taking advantage of the third parameter of the reduce function we know the index of the element we are currently iterating over, therefore also making this function work for arrays that aren't numbers 1 through 10. 通过利用reduce函数的第三个参数,我们知道了当前正在迭代的元素的索引,因此也使此函数适用于非数字1到10的数组。

You could chunk the array, and join the elements with commas and spaces: 您可以对数组进行分块,然后用逗号和空格将元素连接起来:

 var arr = [1,2,3,4,5,6,7,8,9,10,11] chunkArr = arr.reduce((acc, item, index) => { const i = Math.floor(index/2) if(!acc[i]) { acc[i] = [] } acc[i].push(item) return acc }, []) arr = chunkArr.map(arr => arr.join(',')).join(' ') console.log(arr) 

Note, this code works with an odd amount of numbers too. 注意,此代码也可以处理奇数个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM