Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!