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

时间:2016-10-02 09:13:41

标签: javascript html

如何使用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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你可以使用eval做你想做的事情并把它放在try catch中。但你实际上不应该这样做。

&#13;
&#13;
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");
  }

}
&#13;
<input id="auth">
<button type="button" onclick="authorize()">Submit</button>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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");
  }

}
&#13;
<input id="auth">
<button type="button" onclick="authorize()">Submit</button>
&#13;
&#13;
&#13;