javascript 从表单输入后,检查ID是否已存在于数组中

klh5stk1  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(132)

有一个Array,有一个更新Array的函数,输入后会通过Form取.输入ID后,我想检查数组中是否已经存在该ID

输入为1,应该为true。

控制台显示false

const bioData = [
    {id:1}
   ]

const [myArray, setmyArray] = useState(bioData);
const [sid, setId] = useState("");
const handleID = (e) => {
  setId(e.target.value);
}
const updateArray = () =>{
 
 
  const isFound = myArray.some(el => el.id === sid);

  console.log(isFound);

  if (isFound) {
    console.log('✅ array contains object with id = 1');
  }
}

<input type="number" placeholder='Please enter your ID' className='inputelm' onChange={handleID} />
<button className='addbtn btn inputelm' onClick={updateArray}>Add</button>
bnlyeluc

bnlyeluc1#

之所以显示false,是因为bioData[0].id是一个数字,但从input_id.value得到的是一个字符串。输入元素总是返回一个字符串,即使是type="number"。type属性只是为了方便输入,它不会以任何方式解析数据。从input获取值时使用parseInt(),或者更改Initial_data以包含字符串形式的id。

//Filename: App.js

import { useState, useRef } from "react";

export default function App() {
  const bioData = [{ id: 1, name: "harry", score: 12 }];
  const [myArray, setMyArray] = useState(bioData);
  const [sid, setId] = useState();
  const nameInput = useRef();
  const scoreInput = useRef();

  const handleId = (e) => {
//parseInt(value, radix)
//for decimal number system, radix is 10 
    setId(parseInt(e.target.value, 10));
  };

  const updateArray = () => {
    const new_data = {
      id: sid,
      name: nameInput.current.value,
      score: scoreInput.current.value
    };

    const isFound = myArray.some((el) => {
      return el.id === new_data.id;
    });

    if (isFound) {
      console.log("✅ array contains object with id:", new_data.id);
      return;
    }
    setMyArray([...myArray, new_data]);
    console.log("updated");
  };

  return (
    <form>
      <input
        ref={nameInput}
        type="number"
        placeholder="Enter Id"
        onChange={(e) => handleId(e)}
        required
      />
      <input ref={scoreInput} type="text" placeholder="Enter Name" required />
      <input
        id="input-score"
        type="number"
        placeholder="Enter Score"
        required
      />
      <button
        type="submit"
        onClick={(e) => {
          e.preventDefault();
          updateArray();
        }}
      >
        submit
      </button>
    </form>
  );
}
91zkwejq

91zkwejq2#

为此,您应该编写给定的代码

const isFound = myArray.some(el => el._id === sid);

而不是

const isFound = myArray.some(el => el.id === sid);

因为mongodb有as _id元素的id。

相关问题