Build a function forLoop. It takes an array as an argument. Start counting from 0, and, using a for loop, add a string to the array 25 times. But not just any string. If your i value is 1, add the string "I am 1 strange loop."; if your i value is anything else, add the string "I am ${i} strange loops.". (Remember flow control with if and else? And how do we interpolate i?) Then return the array.
Learning online and am having trouble understanding what is needed to return the array with the string added to it 25 times?
function forLoop(array) {
for (let i = 0; i < 25; i++) {
if (i === 1) {
console.log(`${array} I am 1 strange loop.`);
} else {
console.log(`${array}I am ${i} strange loops.`);
}
}
}
forLoop(array);
adds `"I am ${i} strange loop${i === 0 ? '' : 's'}."` to an array 25 times:
TypeError: Cannot read property 'slice' of undefined
-
where you are adding the data in array?arizafar– arizafar2019年06月17日 10:24:37 +00:00Commented Jun 17, 2019 at 10:24
3 Answers 3
You're close. You simply need to push the string to the array, and then return the array at the end.
function forLoop(arr) {
for (let i = 0; i < 25; i++) {
if (i === 1) {
// Use `push` to add the string to the array
arr.push(`I am 1 strange loop.`);
} else {
arr.push(`I am ${i} strange loops.`);
}
}
// Return your array
return arr;
}
// Create the array and pass it into the function
const arr = [];
// `out` captures the returned array
const out = forLoop(arr);
console.log(out);
Comments
You were almost there. Small updates done and posted below
function forLoop(array) {
for (let i = 1; i <= 25; i++) {
array.push(`I am ${i} strange ${i == 1 ? 'loop' : 'loops'}.`)
}
return array;
}
const result = forLoop([]);
console.log(result);
Comments
function forLoop(array: string[]) {
for (let i = 0; i < 25; i++) {
var messsage= 'I am '+i+' strange loop' + (i>0 ? 's.':'.');
array.push (messsage);
console.log(array[i])
}
}
const array:string[]=[];
forLoop(array);
console.log(array.length)