问题描述
标题说明了一切。
我有一个对象数组,如下面的代码所示。每个对象都有两个值,一个类型和一个弱点。我希望用户能够在输入字段中输入类型,然后在提交时,对照所有对象0索引值检查该输入值。匹配后,我想返回匹配对象的1索引值。我想我太新了,错过了简单的设置。有人可以帮忙吗? 我是编程新手(4个月,自学),并且试图弄清楚这一点,所以要保持谦虚。 :)
const form = document.querySelector("#main");
const button = document.querySelector("#submit");
const types = [
{
type: "normal",weakness: "fighting",}
];
let results = [];
form.addEventListener("submit",(e) => {
e.preventDefault();
let result = document.getElementById("type-input").value.toLowerCase();
function checkType() {
if (result.match(types.indexOf[0])) {
console.log('Yay!');
};
};
checkType();
form.reset();
});
解决方法
您可以使用find
检查对象中是否有输入内容
const types = [ { type: "normal",weakness: "fighting",},{ type: "fighting",weakness: "flying,psychic,fairy",{ type: "flying",weakness: "rock,electric,ice",{ type: "poison",weakness: "ground,psychic",{ type: "ground",weakness: "water,grass,{ type: "rock",weakness: "fighting,ground,steel,water,grass",{ type: "bug",rock,fire",{ type: "ghost",weakness: "ghost,dark",{ type: "steel",{ type: "fire",water",{ type: "water",weakness: "grass,electric",{ type: "grass",poison,bug,fire,{ type: "electric",weakness: "ground",{ type: "psychic",weakness: "bug,ghost,{ type: "ice",{ type: "dragon",weakness: "ice,dragon,{ type: "dark",{ type: "fairy",weakness: "poison,dragon",];
input = "dark";
findType = (input) => {
let obj = types.find((o) => o.type == input);
return obj ? obj.weakness : console.log("Object Not FOUND");
};
console.log(findType(input));
,
我的方式。
const types =
[ { type: 'normal',weakness: 'fighting' },{ type: 'fighting',weakness: 'flying,fairy' },{ type: 'flying',weakness: 'rock,ice' },{ type: 'poison',weakness: 'ground,psychic' },{ type: 'ground',weakness: 'water,ice' },{ type: 'rock',weakness: 'fighting,grass' },{ type: 'bug',fire' },{ type: 'ghost',weakness: 'ghost,dark' },{ type: 'steel',fire' },{ type: 'fire',water' },{ type: 'water',weakness: 'grass,electric' },{ type: 'grass',ice' },{ type: 'electric',weakness: 'ground' },{ type: 'psychic',weakness: 'bug,dark' },{ type: 'ice',fire' },{ type: 'dragon',weakness: 'ice,fairy' },{ type: 'dark',fairy' },{ type: 'fairy',weakness: 'poison,dragon' }
]
const myForm = document.querySelector('#my-form')
;
myForm.onsubmit = e =>
{
e.preventDefault()
let result = myForm['type-input'].value.trim().toLowerCase(),rowfind = types.find(x=>x.type===result)
;
if(rowfind) console.log(rowfind.weakness )
myForm.reset()
}
<form action="xxx" id="my-form">
<input type="text" name="type-input" >
<button type="submit"> submit </button>
</form>