Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda