let vegetables = ["cucumbers", "carrots", "tomatoes"];
let upperCase = function() {
for (let i = 0; i <= vegetables.length; i ) {
vegetables[i].toUpperCase();
}
return vegetables[i];
};
console.log(upperCase());
CodePudding user response:
let vegetables = ["cucumbers", "carrots", "tomatoes"];
let upperCase = function(){
return vegetables.map( vegetable => vegetable.toUpperCase())
}
console.log(upperCase()); // [ 'CUCUMBERS', 'CARROTS', 'TOMATOES' ]
// OR YOU CAN ALSO DO THE SAME WITH THIS
let vegetables = ["cucumbers", "carrots", "tomatoes"];
let upperCase = () => vegetables.map( vegetable => vegetable.toUpperCase())
console.log(upperCase());
CodePudding user response:
- you do not replace the array value, upperCase does not work "in place"
- You need to return the result if you
console.log(upperCase())
instead ofupperCase(); console.log(vegetables)
- You overrun the array with your
<=
- it should be<
since arrays are zero based.
Here is your FIXED version
let vegetables = ["cucumbers", "carrots", "tomatoes"];
let upperCase = function() {
for (let i = 0; i < vegetables.length; i ) {
vegetables[i] = vegetables[i].toUpperCase();
}
return vegetables;
};
console.log(upperCase());
and here is a version for 2022
const upperCase = arr => arr.map(item => item && typeof item === 'string' ? item.toUpperCase() : item)
let vegetables = ["cucumbers", "carrots", "tomatoes"];
console.log(upperCase(vegetables));
Breakdown
const upperCase // name of method
= arr // passing something we call arr
=> // arrow function - note we do not need "{ return ... }" if there is only one processing statement
arr.map( // return a map (array) of the passed array, e.g. do not modify the passed array
item => // each element is processed as item
item && typeof item === 'string' // if item is not falsy and is a string
? item.toUpperCase() // return item uppercased
: item) // else return the item (this construct is called a ternary)
CodePudding user response:
I think toUpperCase() method returns a string value, not changes yours, so you need to do like this
vegetables[i] = vegetables[i].toUpperCase();
CodePudding user response:
let vegetables = ["cucumbers", "carrots", "tomatoes"];
let upperCase = function() {
let lst=[]
for (let i = 0; i < vegetables.length; i ) {
lst.push(vegetables[i].toUpperCase());
}
return lst
};
console.log(upperCase());
works this code :)
In for loop should iterate till i< vegetables.length. If not we try to convert uppercase, undefined thing. Then we get error