Javascript 添加数字并得到错误的输出

Javascript 添加数字并得到错误的输出,javascript,Javascript,currentValue为0,selection为3或8,nextValue为23 当得到结果而不是总的附加值时,它变成了0323,而不是23+3,即26 基本问题是JS将“选择”识别为字符串,而不是数值。所以它是“连接”,而不是“添加”。可能选择是字符串,它使所有方程都变成字符串。因此0+'3'+23=0323。使用Number(shipping.overseas)或+shipping.overseas使其成为实数 const [shipping, setShipping] = useStat

currentValue为0,selection为3或8,nextValue为23 当得到结果而不是总的附加值时,它变成了0323,而不是23+3,即26


基本问题是JS将“选择”识别为字符串,而不是数值。所以它是“连接”,而不是“添加”。

可能
选择
是字符串,它使所有方程都变成字符串。因此0+'3'+23=0323。使用
Number(shipping.overseas)
+shipping.overseas
使其成为实数

const [shipping, setShipping] = useState({
        overseas: '3'
});

const handleChange = (e) => {
    setShipping({ overseas: e.target.value});  //can change to 8 or 3
};
const selection = parseInt(shipping.overseas);

console.log(selection);   // result from selection are correct

const getTotal = () => {
    return products.reduce((currentValue, nextValue) => {
        return  (currentValue + selection + nextValue.count * nextValue.price);
    }, 0);
};


const selection=parseInt(shipping.overseas)
shipping.overseas是一个字符串,因此需要将其强制转换为int
const [shipping, setShipping] = useState({
        overseas: '3'
});

const handleChange = (e) => {
    setShipping({ overseas: e.target.value});  //can change to 8 or 3
};
const selection = parseInt(shipping.overseas);

console.log(selection);   // result from selection are correct

const getTotal = () => {
    return products.reduce((currentValue, nextValue) => {
        return  (currentValue + selection + nextValue.count * nextValue.price);
    }, 0);
};
const selection = parseInt(shipping.overseas);
const selection =+shipping.overseas