简体   繁体   中英

How Do I Solve This JavaScript String length Property Error?

I am learning to code and I've been working on this one item for over an hour. The code for the string length property is not correct.

// I have tried:

length.length;
num.toString(); //"6"
length.length; //6

//////The exercise is below

function exerciseThree(str){
  // In this exercise, you will be given a variable, it will be called: str
  // On the next line create a variable called 'length' and using the length property assign the new variable to the length of str
  var length = 'length';
  length.length;
  // Please write your answer in the line above.
  return length;

According to the assignment you have to take the .length property of str , currently you create a string "length" .

The length.length in the following line won't help you, as that takes the length of the string "length" stored in the length variable which is 6, which is probably not the length of the passed str , also you don't do anything with that value.

 function exerciseThree(str) {
   var length = str./*some magic here which i'll leave up to you :)*/;
   return length;
 }

As the instructions in comments ask you to assign the value of variable str to a new variable length which you have to create in the function body and return it. So basically str is the variable which will hold the string value whenever the function exerciseThree is called with a value passed with a (parameter)

Here's the working example of the code:

 function exerciseThree(str){ // In this exercise, you will be given a variable, it will be called: str // On the next line create a variable called 'length' and using the length property assign the new variable to the length of str var length = str.length; // ** storing the "length" of "str" in a "length" variable return length; } // Please write your answer in the line above var name="Alex B"; // string to pass to the function var result = exerciseThree(name); // calling the function and storing "return" value to variable "result" console.log(result); // printing the value of result on the screen.

I do not really know what to teach this exercise.

In the real world, your function would look like this:

function exerciseThree(str) {
    return str.length;
}

excerciseThree("Hokuspokus"); // 10

because:

  1. using the variable only for this purpose is a waste of resources

  2. naming variables in the same way as names of language elements is asking for trouble

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM