I am trying to log to the console the upper case element however, the console throws this error each time: TypeError: arrayNames[i].toUpperCase is not a function
var hello = "Hello, ";
var arrayNames = [];
function greet(name) {
if (name == null) {
console.log(hello + "my friend");
}
//Requirement UpperCase
arrayNames.push(name);
for (var i = 0; i < arrayNames.length; i++) {
if (arrayNames[i] === arrayNames[i].toUpperCase()) {
console.log(hello.toUpperCase() + arrayNames[i].toUpperCase());
}
}
//Requirement last element
if (arrayNames.length > 1) {
var lastElement = arrayNames.pop();
console.log(hello + arrayNames + " and " + lastElement);
}
else {
console.log(hello + arrayNames);
}
}
greet(["James", "Julie", "BEN"]);
You are using toUpperCase on an array.
The problem is the line:
arrayNames.push(name);
You are creating a multidimensional Array.
Use
arrayNames = name;
instead.
You are creating array of array by this
arrayNames.push(name)
Instead do this
arrayNames = name
Which will simply refer to the same array name.
toUpperCase() function can only be called on a string and not an array.
See modified code bellow:
var hello = "Hello, ";
var arrayNames = [];
function greet(name){
if(name==null){
console.log(hello + "my friend")
}
//Requirement UpperCase
arrayNames = name; // NOTICE THE CHANGE HERE
for (var i = 0; i < arrayNames.length; i++) {
if(arrayNames[i]===arrayNames[i].toUpperCase()){
console.log(hello.toUpperCase() + arrayNames[i].toUpperCase());
}
}
//Requirement last element
if(arrayNames.length>1){
var lastElement = arrayNames.pop();
console.log(hello + arrayNames + " and " + lastElement);
}else{
console.log(hello + arrayNames)
}
}
greet(["James", "Julie", "BEN"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With