javascript 我想得到“空缺列数”的总数

bjg7j2ky  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(143)

我想计算“空缺列数”值的总和,那么如何编写函数或逻辑来计算它呢?

const [vacancy, setVacancy] = useState([]); 

console.log(vacancy[0].noOfVacancy) gives the first index output, but I put the for loop and try to get all the values, but its gives an error.

最后,我想得到“空缺列值数量”的总和
请参见此屏幕截图:
enter image description here

import React, { useEffect, useState, useRef } from "react";
import axios from "axios";
import jwt_decode from "jwt-decode";
import { useReactToPrint } from "react-to-print";
import image from "../../../images/back1.jpg";

export default function GenerateVacancyReport() {
  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
  });

  const [vacancy, setVacancy] = useState([]);
  const [filteredResults, setFilteredResults] = useState([]);
  const [searchInput, setSearchInput] = useState("");
  const [companyName, setCompanyName] = useState("");

  useEffect(() => {
    const userToken = localStorage.userToken;
    const decoded = jwt_decode(userToken);
    setCompanyName(decoded.name);
    let name = companyName;
    console.log(name);
    axios
      .get(`http://localhost:5000/vacancy/get/name/${name}`)
      .then((response) => {
        setVacancy(response.data.exsitingVacancies);
      });
  }, [companyName]);

  //search record

  const searchItems = (searchValue) => {
    setSearchInput(searchValue);
    if (searchInput !== "") {
      const filteredData = vacancy.filter((item) => {
        return Object.values(item)
          .join("")
          .toLowerCase()
          .includes(searchInput.toLowerCase());
      });
      setFilteredResults(filteredData);
    } else {
      setFilteredResults(vacancy);
    }
  };
pvcm50d1

pvcm50d11#

下面的代码应该可以完成这个任务

useEffect(() => {
    useEffect(() => {
    let sumVacancies = 0;
    for(let i = 0; i < vacancy.length; i++){

     sumVacancies += +vacancy[i].noOfVacancy;
   
     setTotal(sumVacancies);
    }
    setTotal(sum);
    }, [vacancy])

或使用reduce函数

const [total, setTotal] = useState(0);

useEffect(() => {
let sum = vacancy.reduce((prev,curr) => +prev.noOfVacancy + 
+curr.noOfVacancy)
setTotal(sum);
}, [vacancy])

可以从total访问总和值

相关问题