JavaScript: Type Conversion

1、Display the typeof all variables types

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<p>The typeof operator returns the type of a variable, object, function or expression.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  typeof "john" + "<br>" +
  typeof 3.14 + "<br>" +
  typeof NaN + "<br>" +
  typeof false + "<br>" +
  typeof [1,2,3,4] + "<br>" +
  typeof {name:'john', age:34} + "<br>" +
  typeof new Date() + "<br>" +
  typeof function () {} + "<br>" +
  typeof myCar + "<br>" +
  typeof null;
</script>

</body>
</html>

string
number
number
boolean
object
object
object
function
undefined
object

2、convert a number to a string.

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript String() Method</h2>

<p>The String() method can convert a number to a string.</p>

<p id="demo"></p>

<script>
var x = 123;
var y = 453;
document.getElementById("demo").innerHTML =
  String(x) + "<br>" +
  (y+y) + "<br>" +
  (y+y.toString()) + "<br>" +
  y+y + "<br>" +
  String(123) + "<br>" +
  String(100 + 23);
</script>
</body>
</html>

3、find out if a variables is an Array.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>This "home made" isArray() function returns true when used on an array:</p>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
console.info(myArray.constructor) //function Array() { [native code] }
  return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>
<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>
原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/10609497.html