Tahj Tahj - 2 months ago 7
Javascript Question

Is there a way to build a string out of an array in a specific order?

I'm curious as to whether there's a way to build a string out of an array in a specific order. My code so far:

var pcontent = [ "h", "H", "o", " " ];
var constpass = strConstruct( "pcontent", 1, 2, 3, 0, 2, 3, 0, 2);

function strConstruct ( aname ) {

var newStrs = arguments;
var cs;

for ( var i = 1; i < newStrs.length; i++ ) {
cs = cs + aname[i];
}
return cs;
}

console.log( constpass );


Upon running it I get "contentundefinedcontent"

If it isn't possible, that would be good to know, thanks

Answer

Just few small mistakes

  • You need to pass the variable pcontent to strConstruct not the string "pcontent"

  • And aname[newStrs[i]] instead of aname[i]

  • Initializing cs to an empty string var cs = ""

    var pcontent = ["h", "H", "o", " "];
    var constpass = strConstruct(pcontent, 1, 2, 3, 0, 2, 3, 0, 2);
    
    function strConstruct(aname) {
      var newStrs = arguments;
      var cs = "";
      for (var i = 1; i < newStrs.length; i++) {
        cs = cs + aname[newStrs[i]];
      }
      return cs;
    }
    console.log(constpass);

Comments