我是JavaScript的新手,正在使用Netbeans编写一个简单的网站。由于JavaScript是动态类型语言,我想知道如何在我不确定的情况下找出变量的类型。
例如,如何在下面的代码中找到emailAddress
或domainPart
的变量类型?
function getEmailAndDomainParts(){
var emailAddress = document.getElementById("EmailAddress").value;
var emailPart = emailAddress.substring(0, emailAddress.indexOf("@"));
var domainPart = emailAddress.substring(emailAddress.indexOf("@") + 1);
document.getElementById("Email").value = emailPart;
document.getElementById("Domain").value = domainPart;
}
答案 0 :(得分:1)
// test data
var myArray = ['a', 'b', 'c'];
// the usual typeof isn't very useful
alert(typeof myArray);
// this instance of method tests the array
// to see if it is an instance of the 'Array'
// constructor, which it is!
alert(myArray instanceof Array)
答案 1 :(得分:1)
你可以使用typeof: typeof运算符返回一个字符串,指示未评估操作数的类型
答案 2 :(得分:1)
正如评论中所指出的,您无法检查变量的类型,但可以使用typeof()
检查变量值的类型:
x = "hello";
y = 123;
z = true;
console.log(typeof(x)); //Will return "string"
console.log(typeof(y)); //Will return "number"
console.log(typeof(z)); //Will return "boolean"