js 对数组中的元素每三个一组分别进行处理的方法

首先,有一个数组,里面的数据的长度是3的倍数,然后分别以每三个为一组进行处理。
例如下面这个数组 arr:

let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'l', 'm'];

处理之后的数据为:

["ax", "by", "cz", "dx", "ey", "fz", "gx", "hy", "iz", "jx", "ly", "mz"]

方法 ①

let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'l', 'm'];
let count = 1;

let temp = [];
let result = [];

arr.forEach(function (value) {

    console.log(value);
    temp.push(value);
    if (count % 3 === 0) {

        temp[0] += 'x';
        temp[1] += 'y';
        temp[2] += 'z';

        result = result.concat(temp);

        temp.length = 0;

        console.log('------------');

    }
    count++;

});
console.log(arr);
console.log(result);

使用数组的链接方法concat(),把处理后的数据分别三个一组连接起来,这个方法虽然比较繁琐,但也能实现效果。

方法 ②

let result2 = [];
for (let i = 0; i < arr.length / 3; i++ ) {

    let x = arr[i * 3 ]+'x';
    let y = arr[i * 3 + 1]+'y';
    let z = arr[i * 3 + 2]+'z';

    result2.push(x, y, z);

}

console.log(result2);

结果:
这里写图片描述
3个一组3个一组的放进新数组中,别的方法,暂时还没想到。
示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

    // 要求 对数组 arr 中的元素,每三个一组进行处理, 生成一个新数组
    let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'l', 'm'];

    let count = 1;
    let temp = [];
    let result = [];
    arr.forEach(function (value) {

        console.log(value);
        temp.push(value);
        if (count % 3 === 0) {

            temp[0] += 'x';
            temp[1] += 'y';
            temp[2] += 'z';

            result = result.concat(temp);

            temp.length = 0;

            console.log('------------');

        }
        count++;

    });
    console.log(arr);
    console.log(result);

    let result2 = [];
    for (let i = 0; i < arr.length / 3; i++) {

        let x = arr[i * 3] + 'x';
        let y = arr[i * 3 + 1] + 'y';
        let z = arr[i * 3 + 2] + 'z';

        result2.push(x, y, z);

    }

    console.log(result2);

</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/ithanmang/article/details/82220684