0

So I have a chunk of code... and I want to make it more efficient by condensing it to a few lines instead of twelve. The idea I had was to use the variable of a loop to call each variable in sequence, since the code is just repeated with different numbers each time. Is there any way this could work?

var usetext1 = getText("text1");
var usetext2 = getText("text2");
var usetext3 = getText("text3");
var usetext4 = getText("text4");
var usetext5 = getText("text5");
var usetext6 = getText("text6");
usetext1 = usetext1.toUpperCase();
usetext2 = usetext2.toLowerCase();
usetext3 = usetext3.toLowerCase();
usetext4 = usetext4.toLowerCase();
usetext5 = usetext5.toLowerCase();
usetext6 = usetext6.toLowerCase();

Reduced to something like:

for (var i=2;i<6;i++){
var usetext[i]=getText("text[i]");
usetext[i]=usetext[i].toLowerCase();
Slava.K
  • 3,073
  • 3
  • 17
  • 28
  • Use an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). –  Mar 09 '17 at 14:36
  • Suggestions on how to do that? I tried once but couldn't get it to work. – Connor Davey Mar 09 '17 at 14:38
  • You should then ask about your attempt so that we can show you what you were doing wrong. –  Mar 09 '17 at 14:40
  • Just tried using Christopher Moore's suggestion and it turns out that the medium I am using (code.org) does not allow for the character " ` " other than that, my previous endeavors with arrays were essentially what Duvdevan suggested, save for the .push functions. (that also didn't work) – Connor Davey Mar 09 '17 at 14:51

1 Answers1

1

You can use Template Literals to store the value into an array

var arr = [];
for (var i=1; i <= 6; i++){
    arr.push(getText(`text${i}`).toLowerCase());
}
Christopher Moore
  • 3,071
  • 4
  • 30
  • 46