我正在添加两个数字,但我没有得到正确的值.
例如,1 + 2返回12而不是3
我在这段代码中做错了什么?
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = y + z;
document.getElementById("demo").innerHTML = x;
}Run Code Online (Sandbox Code Playgroud)
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>Run Code Online (Sandbox Code Playgroud)
我有两个只包含数字的字符串:
var num1 = '20',
num2 = '30.5';
Run Code Online (Sandbox Code Playgroud)
我原本以为我可以将它们加在一起,但它们正在被连接起来:
num1 + num2; // = '2030.5'
Run Code Online (Sandbox Code Playgroud)
如何强制将这些字符串视为数字?
很抱歉标题的绕口令,但这是一个非常具体的问题。
目前我有一系列被道具穿过的对象。我正在尝试将所有“分数”值汇总在一起并将其显示在我的应用程序中。
该对象如下所示:
[{'id': '1', 'score': '10'}, {'id': '2', 'score': '20'}, {'id': '3', 'score': '35'}]
Run Code Online (Sandbox Code Playgroud)
在应用程序内部,它被调用如下:
state = {
content: this.props.navigation.getParam('content', false),
}
Run Code Online (Sandbox Code Playgroud)
scoreCount = () => {
const content = this.state.content;
if (content) {
return content.reduce((prev, current) => prev.score + current.score);
} else {
return false;
}
Run Code Online (Sandbox Code Playgroud)
render() {
const score = this.scoreCount()
return (
<View>
<Text>Score:</Text>
{ score ?
<Text>
{ score }
</Text> :
<Text>
0
</Text>
}
</View>
)}
Run Code Online (Sandbox Code Playgroud)
返回时显示“undefined35”
我知道这与在通话时无法使用道具有关,但我不确定如何将分数正确返回给视图
任何帮助将不胜感激