user3640616 user3640616 - 4 months ago 7
Javascript Question

write a for loop that has specific statement for each i in javascript

I'm gonna write a function that do this thing:

foo("abcdefgh") --> "A-Bb-Ccc-Dddd-Eeeee-Ffffff-Ggggggg-Hhhhhhh"
// and so on

function foo(bar) {
return(
bar.charAt(0).toUpperCase(),"-",
bar.charAt(1).toUpperCase(),bar.charAt(1).toLowerCase(),"-",
bar.charAt(2).toUpperCase(),bar.charAt(2).toLowerCase(),bar.charAt(2).toLowerCase(),"-",
bar.charAt(3).toUpperCase(),bar.charAt(3).toLowerCase(),bar.charAt(3).toLowerCase(),bar.charAt(3).toLowerCase(),"-",
bar.charAt(4).toUpperCase(),bar.charAt(4).toLowerCase(),bar.charAt(4).toLowerCase(),bar.charAt(4).toLowerCase(),bar.charAt(4).toLowerCase()
// and so on infinitely
);
}

foo("sadfl");


which code result is:

S-Aa-Ddd-Ffff-Lllll


However, I need to write a code like a code above using
Loop
but I don't know how code it.
bar is not limited and it can be a number infinitely.
like this:

for (i = 0; i < bar.length; i++) {
// a code like that
}

Answer

This is probably what your looking for. Although code could be optimized a bit more.

function foo(bar) {
  var finalStringArray = [];
  for (i = 0; i <= bar.length - 1; i++) {
    var composedString = "";

    for (var b = 0; b <= i; b++) {
      if (b !== 0) {
        composedString += bar.charAt(i).toLowerCase();
      } else {
        composedString += bar.charAt(i).toUpperCase();
      }

    }
    finalStringArray.push(composedString);


  }

  return finalStringArray.join("-");
}