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

186
Visualizações
code check :i expect IndexPlus is 2 but it seems it becom 1+1=11,why?

enter image description here

description :

i expect the indexPlus 2 but it comes 11,what is wrong? and why? see it in line 28 .

code:

var inputArr = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]
console.log('before', inputArr)
var arr = []
//先遍历inputArr确定0的位置
for (key in inputArr) {
  if (inputArr[key] === 0) {
    arr.push(key)
  }
}
//将0移到数组最后面,通过位置交换实现
for (value of arr) {
  for (i = value; i < inputArr.length - 1; i++) {
    swap(i, i + 1)
  }
}

function swap(index, indexPlus) {
  var temp = inputArr[index]
  inputArr[index] = inputArr[indexPlus]
  inputArr[indexPlus] = temp
}
console.log('after', inputArr)

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

0

When you do for (key in inputArr), the keys are strings, not integers. So later when you do swap(i, i + 1), i is a string, and i + 1 does string concatenation, not integer addition.

Change the first loop to loop over indexes, not keys.

var inputArr = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]
console.log('before', inputArr)
var arr = []
//先遍历inputArr确定0的位置
for (let key = 0; key < inputArr.length; key++) {
  if (inputArr[key] === 0) {
    arr.push(key)
  }
}
//将0移到数组最后面,通过位置交换实现
for (value of arr) {
  for (i = value; i < inputArr.length - 1; i++) {
    swap(i, i + 1)
  }
}

function swap(index, indexPlus) {
  var temp = inputArr[index]
  inputArr[index] = inputArr[indexPlus]
  inputArr[indexPlus] = temp
}
console.log('after', inputArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

When you use for ( in ), in every single loop, you will get a key(position) as a string. So when you take it and + 1 you will get result as a string.

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