我有一个对象数组,当用户输入邮政编码并单击时,我想循环遍历该数组,如果用户邮政编码与数组中的邮政编码匹配,则输出结果,如果邮政编码不匹配,则输出另一个结果
我尝试在数组上使用map和forEach,每个都允许我找到邮政编码并提供输出,当邮政编码不匹配时我遇到了麻烦
class PricingTool extends Component {
state = {
zipCode: "",
finalZip: "",
routine: "",
rush: "",
sameDay: "",
city: "",
match: false
};
handleKeypress = e => {
const { zipCode } = this.state;
if (e.which === 13 && zipCode.length === 5) {
console.log("enterrerre");
this.zipcodeHandler();
}
};
zipcodeHandler = () => {
const { zipCode } = this.state;
this.setState({
finalZip: zipCode,
});
};
changeHandler = e => {
e.preventDefault();
if (e.target.value.length <= 5 && !isNaN(e.target.value)) {
this.setState({
[e.target.name]: e.target.value
});
}
};
render() {
const { finalZip, zipCode, match } = this.state;
let searchResult;
if(finalZip){
searchResult = zipCodes.map(cur => {
if (finalZip && finalZip == cur.zip) {
return (
<div className="pricing__searchResult">
<h1 className="pricing__searchResult-1">
We do serve in {cur.city}, Indiana
</h1>
<div className="pricing__searchResult-2">Same-Day</div>
<div className="pricing__searchResult-3">{cur.fees.sameDay}</div>
<div className="pricing__searchResult-4">Rush</div>
<div className="pricing__searchResult-5">{cur.fees.rush}</div>
<div className="pricing__searchResult-6">Routine</div>
<div className="pricing__searchResult-7">{cur.fees.routine}</div>
<div className="pricing__searchResult-8">
Please call us or email info@ccprocess.com to order
</div>
</div>
);
}
});
}
我希望它能够找到用户输入的邮政编码(如果它在数据数组中),如果不在数据数组中,则呈现另一条消息
最佳答案
您可以(并且应该)使用,而不是使用 Array map
方法,该方法会将数组的每个值映射到其他内容(在您的情况下,它只会映射找到的邮政编码)更好的工作方法。 find
方法将找到第一个符合您条件的项目并将其返回,在您的情况下,它可能是 finalZip && (finalZip == cur.zip)
。如果没有找到给定表达式的项目,则返回 undefined
。
render() {
const { finalZip, zipCode, match } = this.state;
let searchResult;
if(finalZip){
searchResult = zipCodes.find(cur => finalZip && (finalZip == cur.zip));
if(searchResult) {
// do something for when the zip code is found
}
else {
// do something when no zip code is found
}
}
}
Array find
方法文档:MDN
关于javascript - 我想循环遍历数组并动态输出结果..如果没有匹配项我想输出另一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56975252/