简体   繁体   中英

Why is my for loop exiting before my condition

import ReactDOM from "react-dom";
import React, { useState } from "react";

const App = () => {
  let [persons, setPersons] = useState([{ id: 11, name: "Arto Hellas" }]);
  const [newName, setNewName] = useState("");

  const check = (arr, name) => {
    let i = 0;
    let checking = true;

    for (i = 0; i < arr.length; i++) {
      console.log(arr[i].name === name);
      if (arr[i].name === name) {
        checking = false;
        break;
      }
      console.log(i);
      return checking;
    }
  };
  const addName = event => {
    event.preventDefault();
    const nameObject = {
      id: newName.length + 1,
      name: newName
    };
    check(persons, nameObject.name)
      ? setPersons((persons = persons.concat(nameObject)))
      : window.alert(`${nameObject.name} is already listed`);
    setNewName("");
    console.log(JSON.stringify(persons));
  };
  const handleNameChange = event => {
    setNewName(event.target.value);
  };

  return (
    <div>
      <h2>Phonebook</h2>
      <form onSubmit={addName}>
        <div>
          name: <input value={newName} onChange={handleNameChange} />
        </div>
        <div>
          <button type="submit">add</button>
        </div>
      </form>
      <h2>Numbers</h2>
      <ul>
        {persons.map(person => (
          <li key={person.id}>{person.name} </li>
        ))}
      </ul>
    </div>
  );
};

export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);

The problem is with my check function which checks if a name exists in the array. I have a for loop that iterates throughout the array but it always stops early. I checked this with console.log(i). If you add Adib once the array looks like this [{"id":11,"name":"Arto Hellas"},{"id":5,"name":"Adib"}] and the value of i is 0 since because before this the length of arr was 1. However if you add Adib again it will do so and value of i is 0 again and not 1

You have return checking in loop. Just put it after } :

const check = (arr, name) => {
  let i = 0;
  let checking = true;

  for (i = 0; i < arr.length; i++) {
    console.log(arr[i].name === name);
    if (arr[i].name === name) {
      checking = false;
      break;
    }
    console.log(i);

  }
  return checking;
};

See full example in playground: https://jscomplete.com/playground/s522611

I'm sorry because I'm not on VScode right now I don't have a plugin which lets me see my brackets more clearly and accidentally had my return statement in a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM