【问题标题】:How Do I Solve This JavaScript String length Property Error?如何解决此 JavaScript 字符串长度属性错误?
【发布时间】:2019-07-24 21:45:58
【问题描述】:

我正在学习编码,并且我已经在这个项目上工作了一个多小时。字符串长度属性的代码不正确。

//我试过了:

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

//////下面是练习题

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;

【问题讨论】:

  • 我对@9​​87654324@ 的来源以及问题所在感到困惑。字符串length的长度应该是6,那有什么问题呢?
  • @Sabrina73 stackoverflow 并非旨在帮助您解决作业。见How to ask。练习中的代码 cmets 会告诉您该做什么。它有一个名为length 的变量并接收一个名为str 的字符串参数。练习要求您将 str 变量的长度存储到 length 变量中。
  • @LéaGris - 对于初学者学习编码的人来说,最好的地方是什么? :) 因为我会不时需要帮助。谢谢!
  • 可能是给你这个练习的人......

标签: javascript string-length


【解决方案1】:

根据分配,您必须获取str.length 属性,当前您创建一个字符串"length"

下一行中的length.length 对您没有帮助,因为它采用存储在length 变量中的字符串"length" 的长度为6,这可能不是传递的@987654327 的长度@,你也不用那个值做任何事情。

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

【讨论】:

  • 谢谢@jonas Wilms。
  • 很高兴为您提供帮助:)
【解决方案2】:

由于 cmets 中的说明要求您将变量 str 的值分配 到一个新变量 length,您必须在函数正文和返回 它。 所以基本上 str 是一个变量,当函数 exerciseThree 被调用时,该变量将保存 string 值,并通过 ( 参数)

这是代码的工作示例:

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.

【讨论】:

    【解决方案3】:

    我真的不知道该练习什么。

    在现实世界中,你的函数应该是这样的:

    function exerciseThree(str) {
        return str.length;
    }
    
    excerciseThree("Hokuspokus"); // 10
    

    因为:

    1. 仅将变量用于此目的是浪费资源

    2. 以与语言元素名称相同的方式命名变量是自找麻烦

    【讨论】:

    • (1) 不同意,考虑每个变量的内存使用情况是浪费时间,编写易于阅读的代码,仅在其中一个有问题时才考虑内存/性能。
    • @Jonas Wilms 'resources' 不仅仅是 RAM,资源也是代码中名称池中的下一个名称。是的,写作风格可以不同。这不是教条。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2020-11-08
    • 2011-06-04
    • 1970-01-01
    • 2011-01-10
    • 2017-12-26
    相关资源
    最近更新 更多