简体   繁体   English

Javascript:与“,”的串联不起作用

[英]Javascript: concatenation with “,” doesn't work

<button onclick="rzut()" />
<div id="wynik" />
<script type="text/javascript">

function rzut() {
document.getElementById("wynik").innerHTML = "Wynik to",Math.floor(Math.random()*6)+1;
}
</script>

For an unknown reason my script show only "Wynik to" and it skips the next part (math.floor etc) 由于未知原因,我的脚本仅显示“ Wynik to”,并且跳过了下一部分(math.floor等)

Okay, let's go over some basics. 好的,让我们来看一些基础知识。

The first thing I would like to bring up is the concept of an Overloaded Operator . 我要提出的第一件事是重载运算符的概念。 An overloaded operator, in short, is an operator that has different behaviour for different operands . 简而言之,重载运算符是对不同的操作数具有不同行为的运算符。 An example of an overloaded operator in Javascript is + . Java中重载运算符的一个示例是+ For example: 例如:

var x = 4 + 4;
// x = 8

As you can see, adding two numeric values has the effect of summing the fields. 如您所见,将两个数值相加具有求和字段的作用。 But what about.. 但是关于..

var x = "4" + "4";
// x = "44";

Well, because the types are strings, it behaves differently, hence it has an overloaded behaviour . 好吧,因为类型是字符串,所以它的行为有所不同,因此它具有重载的行为

The + symbol will summate numeric values, but concatenate string values. +符号将汇总数字值,但字符串值连接起来

Bringing this forward to your example, you want to end up with a string value like.. 将此带到您的示例中,您希望最终得到一个类似..的字符串值。

"Wynik to,3"

Where 3 can vary. 其中3可以变化。 So let's look at it like this.. 因此,让我们这样看。

"Wynik to,X" 

where X is some variable. 其中X是一些变量。 Well.. this means you've got to build the string on the fly.. So following your approach (and not using some of the nice ES6 features that have been introduced), you can use our friendly overloaded + to accomplish this.. 嗯..这意味着您必须动态构建字符串。.因此,按照您的方法(而不使用已引入的一些不错的ES6功能),您可以使用我们友好的重载+来完成此操作。

"Wynik to," + X

Where X is some random number between 1 and 6 therefore.. 因此,X是1到6之间的某个随机数。

"Wynik to " + (Math.floor(Math.random()*6)+1);

So you'll see here, we've got a numeric value on the right hand side and a string value on the left hand side. 因此,您将在这里看到,我们在右侧有一个数字值,在左侧有一个字符串值。

What Javascript does in this situation is what's known as arithmetic promotion , where all operands are promoted to the precision of the highest operand. Javascript在这种情况下所做的就是所谓的算术提升 ,即所有操作数都提升为最高操作数的精度。

In this case, the right hand side of the equation is promoted to a string. 在这种情况下,等式的右侧升为字符串。 Then, as we've seen above, our overloaded operator knows what to do with two strings. 然后,如上所述,我们的重载运算符知道如何处理两个字符串。

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

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