简体   繁体   中英

I don't understand why this function's output is one

This a code a made to move rows in a (3*3) matrix.

const transY =(arr)=> {
    const arrtY = []; 
    for (let i = 1; i < 4; i++) {
        for (let j = 0; j < 3; j++) {
            if (i==3) {
                return arrtY.unshift(arr[3*0+j]);
            }
            return arrtY.push(arr[3*i+j]);
        }
    }
    return arrtY;
}

Expected output (in an array) :


1  2  3       7  8  9       4  5  6
4  5  6  ==>  1  2  3  ==>  7  8  9 ==>  [...]
7  8  9       4  5  6       1  2  3

When I log arrtY in the console I only see 1.

Here's a solution

const transY =(arr)=> {
    const arrtY = []; 
    function rowpush(i) {
        for (let j = 0; j < 3; j++) {
            arrtY.push(arr[3*i+j]);
        }
    }
    rowpush(2);
    rowpush(0);
    rowpush(1);
    return arrtY;
}

Possible solution:

 function transform(arr) { var res = []; for(var i = 6; res.length < 9; i = (i + 1) % 9) res.push(arr[i]); return res; } var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(JSON.stringify(arr)) arr = transform(arr); console.log(JSON.stringify(arr)) arr = transform(arr); console.log(JSON.stringify(arr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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