相关疑难解决方法(0)

添加两个数字会连接它们而不是计算总和

我正在添加两个数字,但我没有得到正确的值.

例如,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)

html javascript

167
推荐指数
8
解决办法
50万
查看次数

如何添加两个字符串就好像它们是数字一样?

我有两个只包含数字的字符串:

var num1 = '20',
    num2 = '30.5';
Run Code Online (Sandbox Code Playgroud)

我原本以为我可以将它们加在一起,但它们正在被连接起来:

num1 + num2; // = '2030.5'
Run Code Online (Sandbox Code Playgroud)

如何强制将这些字符串视为数字?

javascript

159
推荐指数
7
解决办法
17万
查看次数

总结来自 React props 内的对象数组的所有“分数”值

很抱歉标题的绕口令,但这是一个非常具体的问题。

目前我有一系列被道具穿过的对象。我正在尝试将所有“分数”值汇总在一起并将其显示在我的应用程序中。

该对象如下所示:

[{'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”

我知道这与在通话时无法使用道具有关,但我不确定如何将分数正确返回给视图

任何帮助将不胜感激

javascript reactjs react-native

2
推荐指数
1
解决办法
3735
查看次数

标签 统计

javascript ×3

html ×1

react-native ×1

reactjs ×1