Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't know why the results are different. Javascript

let arrays = [ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(arrays);

for(i = 0; i < arrays.length; i++){
    arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays); //[ [ ' ', ' ', '-' ], [ ' ', '-', ' ' ], [ '-', ' ', ' ' ] ]

This is the result I want.

The code below has a different result.

let input = 6;

const diameter = input; //6
const centralValue = Math.ceil(diameter / 2); //3

const reverseArray = (array) => {return array.slice(0).reverse();} //어레이 뒤집어줌
// const makeUpperLeftArrays = function(centralValue){
// }

let createEmptyArray = (number) => {return new Array(number).fill(' ')} //빈 배열 생성

let emptyArray = createEmptyArray(centralValue);

let addEmptyArrays = function(array){
    let addedEmptyArrays = [];
    for(i = 1; i <= centralValue; i++){
        addedEmptyArrays.push(array)
    }
    return addedEmptyArrays;
}
let addedEmptyArrays = addEmptyArrays(emptyArray);


let arrays = addedEmptyArrays
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(arrays);

for(i = 0; i < arrays.length; i++){
    arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays);

please help…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried debugging, taking it out of function, changing the name, but it didn’t work.

>Solution :

Arrays are passed by reference

[...array] will fix your problem

let input = 6;

const diameter = input; //6
const centralValue = Math.ceil(diameter / 2); //3

const reverseArray = (array) => array.slice(0).reverse() //어레이 뒤집어줌


let createEmptyArray = (number) => Array(number).fill(' ') //빈 배열 생성

let emptyArray = createEmptyArray(centralValue);

let addEmptyArrays = function(array){
    let addedEmptyArrays = [];
    for(i = 1; i <= centralValue; i++){
        addedEmptyArrays.push([...array])
    }
    return addedEmptyArrays;
}
let addedEmptyArrays = addEmptyArrays(emptyArray);


let arrays = addedEmptyArrays
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]

console.log(arrays);

for(i = 0; i < arrays.length; i++){
    arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading