繁体   English   中英

如何使用输入检查JS对象是否存在

[英]How to use input to check if JS object exists

如何使用 HTML 输入来检查 javascript 对象是否存在? 如果我在表单中输入person ,它应该给我一个警告,说它存在并重定向页面。 如果我输入不同的东西,它应该得到一个警告,说它不存在。

 <!DOCTYPE html> <html> <input id="auth"> <button type="button" onclick="authorize()">Submit</button> <script> function authorize(){ var auth; auth = document.getElementById("auth"); auth = window[auth]; if (typeof maybeObject !== auth){ alert("it works"); } else if (typeof maybeObject === auth){ alert("it doesnt work") } var person = { firstName : "Billy", lastName : "Bob", age : 20, eyeColor : "purple" }; } </script> </html>

您可以使用 eval 做您想做的事情并将其放入 try catch 中。 但你实际上不应该那样做。

 function authorize() { var auth; var person = { firstName: "Billy", lastName: "Bob", age: 20, eyeColor: "purple" }; auth = document.getElementById("auth").value; try { var t = eval(auth); alert("exists, hello " + t.firstName); } catch (e) { alert("doesn't exist"); } }
 <input id="auth"> <button type="button" onclick="authorize()">Submit</button>

最好是这样的,在下面你可以输入一个人的名字或姓氏,如果存在,你会收到警报:

 function authorize() { var auth; var persons = [{ firstName: "Billy", lastName: "Bob", age: 20, eyeColor: "purple" }]; auth = document.getElementById("auth").value; if (persons.filter(p => p.firstName == auth || p.lastName == auth).length > 0) { alert ("person with that name exists"); } else { alert("no person with given name exists"); } }
 <input id="auth"> <button type="button" onclick="authorize()">Submit</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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