Javascript Permutations magic trick

a 夏天 提交于 2021-01-28 06:33:12

问题


I'm reading some algorithms to try and understand permutations in javascript, and the following one quite stunned me

var permArr = [], usedChars = [];
function permute(input) {
  var i, ch, chars = input.split('');
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0) permArr[permArr.length] = usedChars.join('');
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
}

FYI I found this algorithm on the following website: http://staff.roguecc.edu/JMiller/JavaScript/permute.html

I can see that this algorithm works, but there is a line that confuses me and I can't find anywhere where it works

var i, ch, chars = input.split("");

If i console.log(i) or console.log(ch) before OR after in the code, it returns undefined everywhere. If i remove i and ch, the algorithm does not work anymore.

Can someone explain me this line and how it works? Thanks a lot


回答1:


No Magic involved

var i, ch, chars = input.split('');

declares the variables i, ch and chars and assigns to chars what input.split('') returns.

Basically its equivalent to

var i; // undefined
var ch; // undefined
var chars = input.split(''); // Array of string

This is typically done for the variables to be available across loop iterations (to access previous values).

However...

i is just the loop varible and could be declared inline as in

for (var i = 0; i < chars.length; i++) {

ch could live inside the loop since it is reassigned in the first statement anyway

  for (var i = 0; i < chars.length; i++) {
      var ch = chars.splice(i, 1);

which makes the example confusing indeed (one could say it's poorly written)



来源:https://stackoverflow.com/questions/42071199/javascript-permutations-magic-trick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!