0

when I am swapping the array index then showing the error Cannot set property '3' of undefined in the second swapping line. [str[i],str[j]]=[str[j],str[i]]; .

First swapping is proper work but in second swapping line showing error

var str = [1,2,3]
var result = []
function permutation(str,i){
  if(i===str.length){
    result.push(str)
    return
  }
//   console.log(temp)
  for(let j = 0;j<str.length;j++){
    [str[i],str[j]]=[str[j],str[i]]
    permutation(str,i+1)
    [str[i],str[j]]=[str[j],str[i]];
  }
  return result
}
console.log(permutation(str,0))

0 Answers0