JavaScript data types
String, Number, Boolean, Array, Object, Null, Undefined.
JavaScript has dynamic typing
JavaScript has dynamic typing. This means that the same variable can be used as different types:
Instances
var x; // x 为 undefined var x = 5; // 现在 x 为数字 var x = "John"; // 现在 x 为字符串
JavaScript Strings
Strings are variables that store characters (such as "Bill Gates").
String can be any text in quotes. You can use single or double quotes:
Instance
var carname="Volvo XC60"; var carname='Volvo XC60';
You can use quotes within a string as long as they don't match the quotes surrounding the string:
Instance
var answer="It's alright"; var answer="He is called 'Johnny'"; var answer='He is called "Johnny"';
You will be in Learn more about strings in the advanced section of this tutorial.
JavaScript Numbers
JavaScript has only one number type. Numbers can be written with or without a decimal point:
Example
var x1=34.00; //使用小数点来写 var x2=34; // //不使用小数点来写
Very large or very small numbers can be written using scientific (exponential) notation:
Example
var y=123e5; // 12300000 var z=123e-5; // 0.00123
You will learn more about this tutorial Learn more about numbers in the advanced section.
JavaScript Boolean
Boolean (logical) can only have two values: true or false.
var x=true; var y=false;
Boolean is commonly used in conditional testing. You'll learn more about conditional testing later in this tutorial.
JavaScript Arrays
The following code creates an array named cars:
var cars=new Array(); cars[0]="Saab"; cars[1]="Volvo"; cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):
Instance
var cars=["Saab","Volvo","BMW"];
Array subscripts are zero-based, so no. One item is [0], the second is [1], and so on.
You will learn more about arrays later in this tutorial.
JavaScript Objects
Objects are separated by curly braces. Inside the brackets, the object's properties are defined as name and value pairs (name : value). Properties are separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566};
The object (person) in the above example has three properties: firstname, lastname and id.
Spaces and line breaks don’t matter. Declarations can span multiple lines:
var person={ firstname : "John", lastname : "Doe", id : 5566 };
Object properties are addressed in two ways:
Instances
name=person.lastname; name=person["lastname"];
You will learn more about objects later in this tutorial.
Undefined and Null
Undefined This value means that the variable does not contain a value.
You can clear a variable by setting its value to null.
Instance
cars=null; person=null;
Declare variable type
当您声明新变量时,可以使用关键词 "new" 来声明其类型:
var carname=new String; var x= new Number; var y= new Boolean; var cars= new Array; var person= new Object;
JavaScript 变量均为对象。当您声明一个变量时,就创建了一个新的对象。
以上就是【JavaScript教程】JavaScript 数据类型的内容,更多相关内容请关注PHP中文网(www.php.cn)!