Home > Back-end >  code check :i expect IndexPlus is 2 but it seems it becom 1 1=11,why?
code check :i expect IndexPlus is 2 but it seems it becom 1 1=11,why?

Time:02-18

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)

CodePudding user response:

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)

CodePudding user response:

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.

  • Related