Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 无法在React项目中解析int。请继续获取NaN_Reactjs_Parseint - Fatal编程技术网

Reactjs 无法在React项目中解析int。请继续获取NaN

Reactjs 无法在React项目中解析int。请继续获取NaN,reactjs,parseint,Reactjs,Parseint,好的,所以我目前正在尝试将一个对象中的项目添加到一起。当我尝试用parseInt实际解析项目时,我总是得到NaN 我试着在repl.it上复制它,它工作得很好,我也试着用Number代替parseInt,结果是一样的 class Cart extends Component { constructor(props) { super(props); this.add = this.add.bind(this); } component

好的,所以我目前正在尝试将一个对象中的项目添加到一起。当我尝试用parseInt实际解析项目时,我总是得到NaN

我试着在repl.it上复制它,它工作得很好,我也试着用Number代替parseInt,结果是一样的

    class Cart extends Component {
    constructor(props) {
        super(props);
        this.add = this.add.bind(this);
    }
    componentDidMount() {
        this.props.getCart();
    }

    add(array) {
        let num = [];
        let parse = [];
        console.log(array);
        for (let i = 0; i < array.length; i++) {
            parse.push(array[i].price);
        }
        console.log(parse);
        for (let i = 0; i < parse.length; i++) {
            num.push(parseInt(parse[i]));
        }
        console.log(num);
        let sum = num.reduce((acc, val) => {
            return acc + val;
        }, 0);
        console.log(sum);
    }
    render() {
        const { cart } = this.props.itemReducer;
                this.add(cart);
类购物车扩展组件{
建造师(道具){
超级(道具);
this.add=this.add.bind(this);
}
componentDidMount(){
this.props.getCart();
}
添加(数组){
设num=[];
让parse=[];
console.log(数组);
for(设i=0;i{
返回acc+val;
}, 0);
控制台日志(总和);
}
render(){
const{cart}=this.props.itemReducer;
添加(购物车);
我有一些控制台。日志 第一个显示了我的obj 第二个节目是我在变量[“$379.99”,“$1499.99”]
我实际执行parseInt函数的第三个步骤是当我得到[NaN,NaN]`

时,字符串中有一个
$
符号。请删除该符号并重试

let nanNum=parseInt($1477”)
console.log(nanNum)//这将打印NaN
让parsedNum=parseInt($147,7.05)。替换(/[^0-9\.]+/g,”)
console.log(parsedNum)
这是因为
[“$379.99”,“$1499.99”]
,数组中的项包含的
$
不是导致错误的数字(NaN)

而不是这个,

num.push(parseInt(parse[i]));
你可以这样做

num.push(Number(parse[i].replace(/[^0-9.]/g, "")));

它可能不起作用,因为你前面有一个美元符号,你的值有逗号分隔符。尝试删除逗号,它应该会起作用。效果很好,非常感谢大家总共看了50遍,完全跳过了这个美元符号。@ravibagul91它可以工作,没有任何更改。使用建议值更新答案它正在删除
 .05
来自值。它是parseInt,所以不需要删除小数吗?