[英]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.问题在于我的检查 function 检查数组中是否存在名称。 I have a for loop that iterates throughout the array but it always stops early.
我有一个循环遍历整个数组,但它总是提前停止。 I checked this with console.log(i).
我用 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如果数组看起来像这样
[{"id":11,"name":"Arto Hellas"},{"id":5,"name":"Adib"}]
并且 i 的值是0 因为在此之前 arr 的长度为 1。但是,如果您再次添加 Adib,它将这样做,并且 i 的值再次为 0 而不是 1
You have return checking
in loop.你有
return checking
循环。 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在操场上查看完整示例: 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.很抱歉,因为我现在不在 VScode 上,我没有一个插件可以让我更清楚地看到我的括号,并且不小心将我的 return 语句放在了 for 循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.