繁体   English   中英

如何将 Javascript 中的字符串变量放在一起? 它只是说“对象未定义”

[英]How do I put together string variables in Javascript? It's just saying "Object Undefined"

我已经尝试了很长时间才能使此代码正常工作。 当你需要快速时,我正在编写一个小游戏,所以我做了一个秒表。 但是秒表就是不想工作。 而不是秒表显示Object Undefined ,我不知道为什么。 这是我正在使用的代码:

var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";

    stopwatchFrame+=1;
    stopwatchSeconds = floor(stopwatchFrame/updatesPerSecond);
    stopwatchSecondsString = toString(stopwatchSeconds);
    var = "Total time: " + stopwatchSecondsString + " seconds";

我正在使用一个名为Koda.nu的简单网站,这是一个供年轻人学习 JS 编程的瑞典网站。 一些功能来自它们的内置源。 我是编程新手,所以这就是原因。

您缺少一个变量名称,其中您的值为"Total time: " + stopwatchSecondsString + " seconds"; 它应该是:

var totalTime = "Total time: " + stopwatchSecondsString + " seconds";

另请阅读@Jaromanda X 在评论部分中写的内容。 它应该是这样的:

stopwatchSeconds = Math.floor (stopwatchFrame/updatesPerSecond); stopwatchSecondsString = stopwatchSeconds.toString() ;

我们无权访问您的updatesPerSecond变量,因此也会引发错误。 如果声明,您的代码将像这样工作:

var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
var updatesPerSecond = 0;

stopwatchFrame += 1;
stopwatchSeconds = Math.floor(stopwatchFrame / updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";

你在最后一行没有变量名,如果这就是你的全部代码,那么你不初始化updatesPerSecond,这意味着你没有像

var updatesPerSecond = somenumberhere

如果你命名你的最后一个变量并初始化 updatesPerSecond 那么你应该没问题。

但是我对这个网站一无所知,但我怀疑它已经过时了。 这里有一些建议。

您需要告诉 javascript,该楼层是来自 Math 的 function 所以使用Math.floor ,也许它可以像您一样在这个网站上工作,但请记住,您应该以其他方式使用它。

toString() 不能那样工作。 同样,我不知道他们是否使用了一些不同的方法,但是普通的 js toString() 像数字.toString() 一样工作,你可以将基数作为参数传递,这意味着数字表示的基数(2 表示二进制,16 表示十六进制等)但这是可选的,十进制默认为 10。

不要使用 var 作为声明。 如果变量会更改,请使用 let ,如果不会更改,请使用 const 。 在您的情况下,您应该在任何地方使用 let 。

另一件事是,您可以使用 ++ 运算符将值增加 1,因此不要使用stopwatchFrame+= 1而是使用stopwatchFrame++

最后,您不应该将默认字符串值初始化为“Nothing”,它应该是“”、空字符串或未定义或 null。

我希望这会有所帮助,祝你有美好的一天!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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