admin管理员组

文章数量:1192915

When name is all uppercase, then the function should shout back to the user. For example, when name is "JERRY" then the function should return the string "HELLO, JERRY!" The console logs error: .toUpperCase() is not a function.

var hello = "Hello, ";

function greet(name) {

  if (name == null) {
    console.log(hello + "my friend")
  } else if (name == name.toUpperCase()) {
    console.log(hello.toUpperCase() + name.toUpperCase())
  } else {
    console.log(hello + name);
  }
}

var names = ["jack", "john"]
greet(names);

When name is all uppercase, then the function should shout back to the user. For example, when name is "JERRY" then the function should return the string "HELLO, JERRY!" The console logs error: .toUpperCase() is not a function.

var hello = "Hello, ";

function greet(name) {

  if (name == null) {
    console.log(hello + "my friend")
  } else if (name == name.toUpperCase()) {
    console.log(hello.toUpperCase() + name.toUpperCase())
  } else {
    console.log(hello + name);
  }
}

var names = ["jack", "john"]
greet(names);

Share Improve this question edited Feb 22, 2017 at 14:52 Rikin 5,4732 gold badges16 silver badges22 bronze badges asked Feb 22, 2017 at 14:26 noornoor 1251 gold badge1 silver badge2 bronze badges 3
  • 4 names is an array. An array has no such function. – Denys Séguret Commented Feb 22, 2017 at 14:27
  • That is an array not a string – Lucas Commented Feb 22, 2017 at 14:27
  • Flagging as typographical error. – Eldelshell Commented Feb 22, 2017 at 15:11
Add a comment  | 

6 Answers 6

Reset to default 9

names is an array. An array has no such function.

You probably want to call the greet function on every element of the array:

names.forEach(greet);

If you want the greet function to accept an array as argument then you could do

function greet(name) {
      if (Array.isArray(name)) {
            name.forEach(greet);
            return;
      }
      ...

but this kind of polymorphism is usually seen as a bad practice.

You could apply .toString() first, and then use .toUpperCase():

if (name === name.toString().toUpperCase())

names are array declaration so can't use that type of function, if you want print that array using for loop or using names[1] type

<script>
  var hello = "Hello, ";

  function greet(name) {

    if (name == null) {
      document.write(hello + "my friend")
    } else if (name == name.toUpperCase()) {
      document.write(hello.toUpperCase() + name.toUpperCase())
    } else {
      document.write(hello + name);
    }
  }

  var names = ["jack", "john"]
  greet(names[0]);
  greet(names[1]);
</script>

var hello = "Hello, ";

function greet(names) {
  for (var i = 0; i < names.length; i++) {
    var name = names[i];
    if (name == null) {
      console.log(hello + "my friend")
    } else if (name) {
      console.log('toUpperCase works: ',hello.toUpperCase() + name.toUpperCase())
    } else {
      console.log(hello + name);
    }
  }
}

var names = ["jack", "john"]
greet(names);

If you pass an array into the function, it doesn't work. It's Better now.

Another way, more ES leaning, with error and type handling:

function greet(names) {
    const hello = "Hello"
    if (!names){
        console.log(`${hello} my friend`)
        return;
    }
    // Handles a String
    if (typeof names === "string") {
        console.log(`${hello} ${name}`)
        return;
    }
    // Error Handling for Array
    if (Array.isArray(names) && !names.length) {
        console.error("Passed Array is empty")
        return;
    }
    names.map((name) => {
        const str = `${hello} ${name}`
        name == name.toUpperCase()
            ? console.log(str.toUpperCase())
            : console.log(str)
            // Optional if you have toProperCase as a prototype
            // : console.log(`${hello} ${name.toProperCase()}`)
    })
}

let names = ["jack", "JOHN"]
greet(names)

Results

This will handle an empty array, an array, a string and empty or falsy calls. If you had a need to also handle an Object, it could be done as well with additional code.

Bonus Material

Avoiding a discussion on if using prototypes this way is good or bad, just showing a reasonable way it could be done if desired.

toProperCase prototype:

String.prototype.toProperCase =
    String.prototype.toProperCase ||
    function (word) {
        if (!word) {
            word = this
        }
        if (word) {
            let str = word.toLowerCase().split(" ")
            for (let i = 0; i < str.length; i++) {
                str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1)
            }
            return str.join(" ")
        } else {
            // ERROR message
            // RETURNS var passed to it. If there is an issue it just returns the same value.
            console.log(
                "The util function toProperCase() \nis not able to do anything with '" +
                    word +
                    "' a typeof",
                typeof word,
                "\nReturning variable in same state."
            )
            return word
        }
    }

Since names is an array, you have to loop it first to get the value inside array. Or perhaps you can try my code:

var hello = "Hello, ";

function greet(name) {
    //loop name with for of
    for (let val of name) {
        if (val == null) {
            console.log(hello + "my friend")
        } else if (val == val.toUpperCase()) {
            console.log(hello.toUpperCase() + val.toUpperCase())
        } else {
            console.log(hello + val);
        }
    }
}

var names = ["jack", "john"]
greet(names);

本文标签: javascripttoUpperCase() is not a functionStack Overflow