what is missing so that the result is equal to that of the example

0
function armarTexto(arreglo){
    var resultado="";

    for (var i in arreglo){
           resultado+= "propiedad"+i+"->"+arreglo[i]+";";
    }
    return resultado;
}

What is the error?

    
asked by Juan Pinzón 10.01.2017 в 03:32
source

4 answers

1

I'll give you two ways to do it:

  • via ES6 (new version)
  • via ES5 (old version)

ES6

In ES6 came a feature called rest parameters which allows you to interpret parameters of a function as if it were an array. In this example I show you this feature, however, you can change it to pass an array directly .

function arrayToObjectStr (...data) {
  const obj = {};
  data.forEach((val, i) => {
  	obj['propiedad${i+1}'] = val;
  });
  let toStr = '';
  for (let [k, v] of Object.entries(obj)) {
  	toStr += '${k}->${v};';
  }
  return toStr;
}

if (Object.entries) {
  console.log(arrayToObjectStr(4, 8, 12, 15)); 
} else {
  console.warn('Lo siento, su navegador no soporta ES2015');          
}

ES5

Doing it in ES5 is very similar, apart from being -for the moment- cross browser.

function arrayToObjectStr (data) {
  var obj = {};
  data.forEach(function (val, i) {
    obj['propiedad' + (i+1)] = val;
  });
  var toStr = '';
  for (var key in obj) {
    toStr += key + '->' + obj[key] + ';';
  }
  return toStr;
}

console.log(arrayToObjectStr([4, 8, 12, 15]));
    
answered by 10.01.2017 в 14:34
0

Depending on what you are asking, you should do the following:

function armarTexto(arreglo)
{
   var resultado="";
   for (var i = 1; i <= 4; i++){
       resultado+= "propiedad"+i+"->"+arreglo[i]+";";
    }
    return resultado;
}
    
answered by 10.01.2017 в 04:03
0

Modifying the for and making a small adjustment to how to print the position of the fix can fix the problem:

var arreglo = [4,3,2,1];
var resultado = "";
for (i = 1; i <= arreglo.length; i++){
		resultado += "propiedad" + i + "->" + arreglo[i - 1] +";";
}
alert(resultado);
    
answered by 10.01.2017 в 17:10
0

According to I understand the function must return an object, I work with this

var regresaObjeto = function (arreglo) {
    var result = {};
    for (var i = 0; i < arreglo.length; i++) {
        result["Propieda" + (1 + i)] = arreglo[i];
    }
    return result;
}
    
answered by 10.01.2017 в 17:24