Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
How to modify a global variable inside a function in javascript, i.e. modify variable in-place

So, below you can find my (very basic and unoptimized) solution to Leetcode's challenge 189 'Rotate Array'. The target of this challenge is posed as follows: Given an array, rotate the array to the right by k steps, where k is non-negative.

Now, my solution is not accepted as somehow the global variable nums remains unchanged after the function call. Why is that? Somehow nums is treated as local variable and doesn't change the passed-in global variable nums. I get that it's probably because of how javascript treats variable scopes but I don't seem to find resources that can help me understand this example.

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    array2 = Array.from(nums)
    nums.map((num) => {
        array2[(nums.indexOf(num)+k)%nums.length] = num
    })
    nums = Array.from(array2)
    console.log(nums) // returns expected answer
};
Your input
[1,2,3,4,5,6,7]
3

Your stdout
[5,6,7,1,2,3,4]

Your answer
[1,2,3,4,5,6,7]

Expected answer
[5,6,7,1,2,3,4]

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The map function does not modify the original array. Additionally, you seem to be using it incorrectly.

You are using map to set the values of array2 and then setting nums to a copy of array2. This will not modify the original object contained in nums.

Of course, if you log nums within the function, it will give you the updated value, but this value is scoped within the function and won't be accessible outside.

Instead of array methods, for this type of impure programming, you should use a for loop.

var rotate = function(nums, k) {
    array2 = Array.from(nums);
    for (const i in nums) nums[i] = array2[(i+k)%nums.length];
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Your approach is correct, but here is the issue:

var rotate = function(nums, k) {
    array2 = Array.from(nums)
    nums.map((num) => {
        array2[(nums.indexOf(num)+k)%nums.length] = num //Making changed to array2
    })
    nums = Array.from(array2) //Completely changing the reference of nums
    console.log(nums) // returns expected answer
};

let nums =  [1,2,3,4,5,6,7];
rotate(nums,3); 
console.log(nums); //Original nums still as it is

If you look at the above code, nums is actually not changing. Reason being you are creating a completely new array array2. Inside your .map(), you are making all sorts of changing to it and assigning that back again to nums. But the reference of the original nums is unchanged.

You should actually be making change to your nums and using array2 for help:

var rotate = function(nums, k) {
        array2 = Array.from(nums)
        array2.forEach((num) => {
        nums[(array2.indexOf(num)+k)%array2.length] = num
        })
        console.log(nums) // returns expected answer
    };

let nums =  [1,2,3,4,5,6,7];
    rotate(nums,3);
    console.log(nums);

PS: .map() is when you want a new transformed array returned. Otherwise you can simply use .forEach, or a for loop.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda