function armarTexto(arreglo){
var resultado="";
for (var i in arreglo){
resultado+= "propiedad"+i+"->"+arreglo[i]+";";
}
return resultado;
}
What is the error?
I'll give you two ways to do it:
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]));
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;
}
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);
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;
}