constructor 属性返回变量或对象的构造函数。判断是否为日期,数组的例子

时间:2024-01-02 17:10:52

constructor 属性返回变量或对象的构造函数。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>constructor 属性返回变量或对象的构造函数。</title>
</head>
<body> <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"john".constructor + "<br>" +
(3.14).constructor + "<br>" +
false.constructor + "<br>" +
[1,2,3,4].constructor + "<br>" +
{name:'john', age:34}.constructor + "<br>" +
new Date().constructor + "<br>" +
function () {}.constructor;
</script> </body>
</html>

运行结果:

function String() { [native code] }
function Number() { [native code] }
function Boolean() { [native code] }
function Array() { [native code] }
function Object() { [native code] }
function Date() { [native code] }
function Function() { [native code] }

判断是否为日期,数组的例子


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>判断是否为日期、数组</title>
</head>
<body>

<p>判断是否为日期。</p>
<p id="demo1"></p>
<p>判断是否为数组。</p>
<p id="demo2"></p>
<script>
  var myDate = new Date();
  var fruits = ["Banana", "Orange", "Apple", "Mango"];
  document.getElementById("demo1").innerHTML = isDate(myDate);
  document.getElementById("demo2").innerHTML = isArray(fruits);
  function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
  }
  function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
  }
</script>

</body>

</html>

 

测试结果

判断是否为日期。

true

判断是否为数组。

true