JavaScript-程序员参考-三-

59 阅读1小时+

JavaScript 程序员参考(三)

原文:JavaScript Programmer's Reference

协议:CC BY-NC-SA 4.0

五、JavaScript 全局对象参考

因为 JavaScript 的基本特性之一是原型继承,所以它没有数组或字符串之类的基类。相反,JavaScript 有一组基本对象,相同类型的其他对象可以从这些对象继承它们的属性和方法。这些基本对象位于全局范围内(在浏览器中是window对象),因此可以随时访问。

本章为主要的 JavaScript 全局对象ArrayBooleanDateNumberRegExpString提供参考。它还包含了针对Math对象的文档,与其他对象不同,它不作为继承的基础对象(你永远不会创建新的Math对象),而是作为数学方法和函数的库。该引用按对象名称的字母顺序排列,每个对象按属性和方法组织。此外,还有其他几个保存在全局范围内的变量和函数非常有用,我们将在本章的最后一节“其他全局变量和函数”中介绍它们

排列

JavaScript Array对象是数组的全局构造函数。数组是数字索引值的简单数据结构。在 JavaScript 中,使用熟悉的方括号符号来访问数组;例如,arrayName[12]将访问存储在索引 12 处的数组的值。JavaScript 数组有以下基本属性:

  • JavaScript 数组是零索引的,因此数组中的第一个元素位于索引 0 处,而不是索引 1 处。
  • JavaScript 数组具有动态长度,因此您不必定义一个数组将有多少个元素。
  • 当您访问不存在的元素时,JavaScript 数组不会抛出越界错误。相反,JavaScript 返回值undefined
  • JavaScript 数组可以索引任何类型的有效 JavaScript 元素:字符串、数字、其他数组(JavaScript 就是这样实现多维数组的),甚至对象。JavaScript 数组也可以包含多种类型的元素,因此可以将对象、字符串和布尔值作为不同的元素放在一个数组中。
  • JavaScript 数组本身就是对象——它们从全局Object对象继承而来,可以访问对象的所有特性。

Array对象有几个管理数组的有用方法。关于 JavaScript 数组的详细讨论,请参见第二章中的“数组”一节。

构造新数组有两种主要方法:直接使用Array对象作为构造函数,或者使用文字符号。

如果使用Array对象作为构造函数,该方法将接受一个可选参数,该参数是一个表示数组长度的整数。该整数应介于 0 和 2³²¹ 之间;任何其他值都会抛出一个RangeError异常。如果提供了参数,新数组将用指定数量的元素初始化(每个元素将被设置为undefined)。从实践的角度来看,因为 JavaScript 数组的长度是动态的,并且 JavaScript 在试图访问不存在的元素时不会抛出越界错误,所以创建预定义长度的数组没有多大意义。

要用数据 构造一个数组,只需将数据作为逗号分隔的列表包含在构造函数或文字符号中。

语法

var exampleArray = new Array(length);             // Create an array using the Array constructor.
var exampleArray = [];                            // Create a new array literal.

例题

// Initialize an empty array
var myArray = new Array();                        // myArray will be empty--have a length of 0.
var myOtherArray = [];                            // Literal notation
var myLongArray = new Array(100);                 // length is 100.
alert(myLongArray[47]);                           // will alert "undefined"

// Initializing new arrays with values
var myFilledArray = new Array("this", "and", "the", "other");
var myIntegerArray = new Array(202, 53, 12, 0);
var myOtherFilledArray = ["more", "like", "this"];
var mySmallArrayOfDecimals = [0.1, 0.4];

// Constructing multidimensional arrays
var row1 = [1, 2, 3];
var row2 = [4, 5, 6];
var row3 = [7, 8, 9];
var array3by3 = [row1, row2, row3];               // array3by3 is now a multidimensional array
alert(array3by3[1][1]);                           // alerts 5

// Constructing arrays of objects
var object1 = {
    "myName" : "object1"
};
var object2 = {
    "myName" : "object2"
};
var object3 = {
    "myName" : "object3"
};

var arrayOfObjects = [object1, object2, object3]; // arrayOfObjects now contains the objects
alert(arrayOfObjects[1].myName);                  // alerts "object2".

数组属性

JavaScript Array全局对象只有几个默认属性,其中大部分都是从Object继承的。Array自己定义的唯一默认属性是length属性。

长度

每个数组都有一个length属性,对应于数组中元素的总数。空数组的length为 0。如果一个数组有元素,那么最后一个元素的索引将是length–1,因为 JavaScript 数组是零索引的。

语法

exampleArray.length;

例题

var myArray = ["this", "is", "an", "array"];
alert(myArray.length);              // alerts 4
alert(myArray[myArray.length]);     // alerts "undefined"; there is no such element with index of 4.
alert(myArray[myArray.length -1]);  // alerts "array".

数组方法

对象提供了几个非常有用的方法来操作数组。

concat( )

Array.concat()方法将两个(或更多)数组连接成一个新数组。它不会影响目标阵列。

语法

var newArray = exampleArray.concat(array1, array2, ..., arrayN);

例题

var array1 = ["bunnies", "kittens", "puppies"];
var array2 = ["velociraptors"];
var array3 = array1.concat(array2); // array3 will now contain ["bunnies", "kittens", "puppies", "velociraptors"].

索引( )

Array.indexOf()提供了一种简单的方法来搜索数组中的特定值。如果提供的元素出现在数组中,此方法将返回其第一个匹配项的索引。如果提供的元素不在数组中,此方法将返回–1。

该方法还采用一个可选的整数参数,该参数被解释为搜索的起始索引。正整数被解释为从数组开头开始的起始索引,负整数被解释为从数组结尾开始的起始索引。在这两种情况下,搜索都进行到数组的末尾。

语法

exampleArray.indexOf(element, startingIndex);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var indexOfKittens = myArray.indexOf("kittens");             // 1
var indexOfVelociraptors = myArray.indexOf("velociraptors"); // -1
var indexOfPuppies = myArray.indexOf("puppies", -1);         // this will return -1 because puppies is not contained within the subset specified by the starting index.
var indexOfPuppiesForReal = myArray.indexOf("puppies", -3);  // 2

join( )

Array.join() 将一个数组的所有元素串联成一个字符串。该方法采用一个可选参数作为分隔符;如果未指定参数,则默认使用逗号。

语法

exampleArray.join(separator);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var strCuteThings = myArray.join();                          // strCuteThings now contains "bunnies,kittens,puppies,ponies,polar bear cubs"
var sentence = myArray.join(" are cute and ") + "are cute!"; // sentence now contains "bunnies are cute and kittens are cute and puppies are cute and ponies are cute and polar bear cubs are cute!"

lastIndexOf( )

Array.lastIndexOf()提供了一个有用的方法来查找一个数组中最后一个出现的元素。如果找到该元素,此方法将返回最后一个匹配项的索引;如果没有找到该元素,它将返回 1。

Array.indexOf()一样,这个方法采用一个可选的整数参数作为起始索引。正整数被解释为从开始的起始索引,搜索将进行到结尾。负整数将被解释为从末尾开始的索引,搜索将继续到数组的开头。

语法

exampleArray.lastIndexOf(element, startingIndex);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs", "bunnies", "kittens"];
alert(myArray.lastIndexOf("bunnies"));                       // alerts 5
alert(myArray.lastIndexOf("ponies", 4));                     // alerts -1
alert(myArray.lastIndexOf("kittens", -2));                   // alerts 1

pop( )

Array.pop() 从数组中移除最后一个元素,并返回该元素。对比Array.shift()

语法

exampleArray.pop();

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var cubs = myArray.pop(); // myArray is now ["bunnies", "kittens", "puppies", "ponies"] and cubs is now "polar bear cubs"

push( )

Array.push()方法提供了一种向数组添加新元素的方法。新元素需要使用文字符号来指定。方法返回数组的新长度。

请注意,一个数组可以被推入另一个数组。这是创建多维数组的一种方式。(要将数组连接在一起,请使用Array.concat()。)

语法

exampleArray.push(element1, element2, ..., elementN);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var newLength = myArray.push("chinchillas", "sugar gliders"); // newLength is 7
var predators = ["velociraptors", "wolves"];
newLength = myArray.push(predators);                          // newLength is 8 (not 9!)
alert(myArray[7]);                                            // alerts "velociraptors,wolves"
alert(myArray[7][1]);                                         // alerts "wolves"

反向()

Array.reverse() 反转数组中元素的顺序。它“就地”执行此操作,这意味着当调用此方法时,数组本身会反转。

语法

exampleArray.reverse();

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
myArray.reverse(); // myArray is now  ["polar bear cubs", "ponies", "puppies", "kittens", "bunnies"];

shift( )

Array.shift() 从数组中移除第一个元素并返回该项。对比Array.unshift()Array.pop()

语法

exampleArray.shift();

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var bunnies = myArray.shift(); // myArray is now ["kittens", "puppies", "ponies", "polar bear cubs"] and bunnies is now "bunnies"

slice( )

方法根据指定的索引范围从数组中移除元素。该方法将两个整数作为参数:开始索引和结束索引。该方法将选择从起始索引开始到结束索引结束的元素(但是它将而不是包括由结束索引指定的元素)。正整数被解释为从数组开始的索引,负整数被解释为从数组结束的索引。方法将指定的元素作为新数组返回,并且不影响目标数组。

语法

exampleArray.slice(startingIndex, endingIndex);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var commonPets = myArray.slice(1, 2); // commonPets is now ["kittens", "puppies"];
var carnivores = myArray.slice(4, 5); // carnivores is now ["polar bear cubs"];

sort( )

Array.sort() 将对一个数组的元素进行排序。如果没有指定参数,数组将按字母升序排序。

如果字母升序没有用,该方法可以将排序函数作为参数,或者作为内联函数,或者作为命名函数。排序函数必须期望两个参数,ab(将是数组元素),并比较它们。如果a是比b更低的索引,该函数应该返回 1。如果两者相等,函数应该返回 0。如果b是一个比a更低的索引,函数应该返回 1。这使得对数组进行复杂的排序成为可能。

但是,请注意,在大型数组上运行复杂的排序函数可能会很昂贵,因为Array.sort()将在每个元素上运行该函数。“复杂”和“大”的确切构成取决于您的具体情况,因此如果您发现您的应用运行缓慢,并且它正在进行复杂排序,这是寻找优化性能机会的合理位置。

语法

exampleArray.sort(sortMethod);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
myArray.sort(); // myArray is now ["bunnies", "kittens", "polar bear cubs", "ponies", "puppies"]
var arrayOfIntegers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
arrayOfIntegers.sort(); // arrayOfIntegers is now [0, 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], which is possibly not useful
function mySortingFunction(a, b) {
    return a-b;
}
arrayOfIntegers.sort(mySortingFunction); // arrayOfIntegers is now [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

拼接()

Array.splice() 提供了操作数组的通用方法。该方法可以在数组中添加或移除元素,并且目标数组被就地操作。该方法将以数组对象的形式返回从数组中移除的任何元素。

该方法有三个参数。第一个参数是一个整数,是操作的起始索引,并且是必需的。和其他以索引为参数的Array方法一样,正整数被解释为从数组开头开始的索引,负整数被解释为从数组结尾开始计数的索引。

第二个参数是必需的,可以是 0 或正整数。它指定要从数组中移除多少个元素。如果设置为 0,则不会删除任何元素。

第三个参数是可选的,它是通过串联添加到数组中的新项。这可以是一个文字列表或另一个数组对象。

语法

exampleArray.splice(startingIndex, numberOfElements, item1, item2, item3, ..., itemN);

或者

exampleArray.splice(startingIndex, numberOfElements, arrayOfNewItems);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var arrayOfPuppies = myArray.splice(2, 1);         // This just removes "puppies" from myArray. arrayOfPuppies  is now ["puppies"]
var arrayOfKittens = myArray.splice(1, 1, "maru"); // arrayOfKittens is now ["kittens"] and myArray is now ["bunnies", "maru", "ponies", "polar bear cubs"];
var arrayOfPredators = ["velociraptors", "wolves"];
myArray.splice(2, 0, arrayOfPredators);            // myArray is now ["bunnies", "maru", "ponies", ["velociraptors", "wolves"], "polar bear cubs"]

toString( )

Array.toString()将数组的所有元素连接成一个逗号分隔的字符串。这个方法和不带参数调用Array.join()完全一样。

语法

exampleArray.toString();

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
var strCuteThings = myArray.toString(); // strCuteThings now contains "bunnies,kittens,puppies,ponies,polar bear cubs"

unshift( )

Array.unshift() 将指定的元素添加到一个数组的开头。对比Array.shift()Array.push()

语法

exampleArray.unshift(element1, element2, ..., elementN);

例题

var myArray = ["bunnies", "kittens", "puppies", "ponies", "polar bear cubs"];
myArray.unshift("chinchillas"); // myArray is now ["chinchillas", "bunnies", "kittens", "puppies", "ponies", "polar bear cubs"]

布尔代数学体系的

JavaScript Boolean是布尔(真或假)数据类型的对象包装器。JavaScript 也有布尔原语truefalse;如果您试图访问一个布尔原语的Boolean属性或方法,JavaScript 会悄悄地用一个Boolean对象包装它,以提供所请求的功能。

您可以使用Boolean对象作为构造函数来构造一个新的布尔对象,它带有一个可选参数。如果参数为0null""falseundefinedNaN(或者根本不指定),那么新的Boolean对象的 value 属性将为 false。否则,它将被设置为 true(即使在指定字符串值为“false”的情况下)。请记住,当用构造函数创建Boolean对象时,结果是一个对象,而不是原始值。注意,从实际角度来看,您很少需要创建Boolean对象,因为 JavaScript 会为您包装布尔原语。

语法

var exampleBoolean = new Boolean(parameter);

例题

var newBooleanObject = new Boolean(false);  // create new Boolean object with a value of false
var newBooleanPrimitive = false;            // create new primitive boolean
alert(typeof newBooleanObject);             // will alert "object"
alert(typeof newBooleanPrimitive);          // will alert "boolean"

// This alert will happen because objects cast to true, even though the value is false
if (newBooleanObject) {
  alert("newBooleanObject is true!");
}

// This alert will not happen because it is a primitive set to false.
if (newBooleanPrimitive) {
  alert("newBooleanPrimitive is true!");
}

布尔方法

布尔对象为确定它们的值提供了两种有用的方法。这些最常用于铸造的情况。

toString( )

Boolean.toString()方法将返回一个表示布尔值的字符串(“真”或“假”)。

语法

exampleBoolean.toString();

例题

var myBoolean = false;              // Create a new boolean with the false primitive
alert(myBoolean.toString());        // alerts "false"
var myOtherBoolean = new Boolean("false");
alert(myOtherBoolean.toString());   // alerts "true"
var myLiteralBoolean = true;
alert(myLiteralBoolean.toString()); // alerts "true"

valueOf( )

Boolean.valueOf()方法将布尔值作为原始值返回(与Boolean.toString()相反,后者将布尔值作为字符串返回)。

语法

exampleBoolean.valueOf();

例题

var newBool = false                 // Create a new boolean with the false primitive
var otherBool = newBool.valueOf();
alert(typeof otherBool);            // will alert "boolean"
alert(otherBool.toString());        // will alert "false"

日期

Date对象用于返回日期,日期的形式由它的许多构造函数生成。对象的每个实例都是一个以毫秒为单位的值,并且相对于 1970 年 1 月 1 日的零点。所有正值都表示 1970 年 1 月 1 日之后的日期。所有负值都表示 1970 年 1 月 1 日之前的日期。

在对Date对象使用参数时,请遵循年、月、日、小时、分钟、秒和毫秒的顺序。浏览器在 UTC()方法中将时间存储为毫秒值。UTC,也简称为世界时,代表协调世界时,实质上是从 1970 年 1 月 1 日开始的格林威治标准时间。返回给浏览器的时间取自您的操作系统,所以请记住,不正确的系统时间可能会导致您在使用Date对象时遇到任何问题。

对象很复杂,但是提供了许多方便的方法来管理、比较和格式化日期。稍加练习,它们会变得更容易使用。

使用Date对象作为构造器来构造日期。构造函数接受一个可选参数,该参数可以是一个整数(表示自 1970 年 1 月 1 日零时起的毫秒数,可以是正数、负数或 0)、一个根据Date.parse()中的要求格式化的信息字符串或一组表示所需年、月、日等的整数。如果没有指定参数,则返回当前日期。

语法

var exampleDate = new Date();
var exampleDate = new Date(milliseconds);
var exampleDate = new Date(string);
var exampleDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);

例子

var currentDate = new Date();  // No arguments so the current date is returned
alert(currentDate.getDate() ); // alerts the current day of the month (see getDate() method, below).

日期方法

对象提供了几个非常有用的方法来操作和比较日期。

get data()键

Date.getDate()方法用于返回Date对象的月份日期。

语法

exampleDate.getDate();

例子

var dateObject = new Date();   // Create new date object with today's date.
alert(dateObject.getDate());   // alerts today's day of the month.

getDay( )

Date.getDay()方法用于返回Date对象的星期几。天是零索引的,星期日是 0。

语法

exampleDate.getDay();

例子

var dateObject = new Date();     // Create new date object for today
alert(dateObject.getDay());      // Alerts today's day of the week

getFullYear( )

Date.getFullYear()方法用于返回代表年份的四位数,这是从您的操作系统指定的日期获取的,并由Date对象使用。

语法

exampleDate.getFullYear();

例子

var dateObject = new Date();     // Create new date object with today's date
alert(dateObject.getFullYear()); // Alerts the year

getHours( )

Date.getHours()方法用于返回一天中的小时,该小时取自操作系统指定的日期,并由Date对象使用。返回的小时基于 24 小时制。

语法

exampleDate.getHours();

例子

var dateObject = new Date();     // Create new date object with today's date
alert(dateObject.getHours());    // Alerts the current hour.

getMilliseconds( )

Date.getMilliseconds()方法用于返回一个 0 到 999 之间的数字,代表Date对象的毫秒数。

语法

exampleDate.getMilliseconds();

例子

var dateObject = new Date();         // Create new date object as of that moment
alert(dateObject.getMilliseconds()); // Alerts the milliseconds at the time when dateObject was formed.

get inuts()

Date.getMinutes()方法用于返回一天中的分钟。

语法

exampleDate.getMinutes();

例子

var dateObject = new Date();         // Create new date object with today's date
alert(dateObject.getMinutes());      // Alerts the minutes of the hour

getMonth( )

Date.getMonth()方法用于返回一年中的月份,该月份取自操作系统指定的日期,并由Date对象使用。返回值是月份的数字表示,而不是月份名称。月份是零索引的,因此一月是 0,十二月是 11。

语法

exampleDate.getMonth();

例子

var dateObject = new Date();         // Create new date object with today's date
alert(dateObject.getMonth());        // Alerts the month

getSeconds()

Date.getSeconds()方法 用于返回分钟的秒,该秒取自操作系统指定的日期,由Date对象使用。

语法

exampleDate.getSeconds();

例子

var dateObject = new Date();         // Create new date object with today's date
alert(dateObject.getSeconds());      // Alerts the seconds

getTime()

Date.getTime()方法 用于返回自 1970 年 1 月 1 日以来经过的毫秒数,该时间取自您的操作系统指定的日期,并由Date对象使用。返回值以毫秒为单位。

这似乎是一种奇怪而武断的表示日期的方式,但是它使日期数学化(比较、加法和减法等)。)相当容易。

语法

exampleDate.getTime();

例子

var dateObject = new Date();           // Create new date object with today's date
alert(dateObject.getTime());           // Alerts the milliseconds since January 1, 1970

getTimezoneOffset()

Date.getTimezoneOffset()方法 用于返回 GMT 与客户端计算机上的时间之差对应的分钟数,这是您的操作系统指定的时间,由Date对象使用。

语法

exampleDate.getTimezoneOffset();

例子

var dateObject = new Date();           // Create new date object with today's date
alert(dateObject.getTimezoneOffset()); // Alerts the timezone offset

getutcdate()

Date.getUTCDate()方法 用于返回操作系统指定的一个月中的某一天,用 UTC 时间或不含本地时差的时间表示。返回值是 1 到 31 之间的值。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCDate();

例子

var dateObject = new Date();           // Create new date object with today's date
alert(dateObject.getUTCDate());        // alerts the day of the month

getUTCDay()

Date.getUTCDay()方法 用于返回一周中的某一天(0 到 6,表示一周中的七天),由操作系统指定,用 UTC 时间或不含本地时差的时间表示。返回值是 0 到 6 之间的值。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCDay();

例子

var dateObject = new Date();            // Create new date object with today's date
alert(dateObject.getUTCDay());          // Alerts the day of the week

getUTCFullYear()

Date.getUTCFullYear()方法 用于返回操作系统指定的当前年份的四位数表示,用 UTC 时间或不含本地时差的时间表示。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCFullYear();

例子

var dateObject = new Date();            // Create new date object with today's date
alert(dateObject.getUTCFullYear());     // Alerts the current year

getUTCHours()

Date.getUTCHours()方法用于返回一天中的小时,用 UTC 时间或不带本地时差的时间表示。返回的值是从 00 到 23 的值,使用 24 小时制。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCHours();

例子

var dateObject = new Date();            // Create new date object with today's date
alert(dateObject.getUTCHours());        // Alerts the current hour of the day

getUTCMilliseconds()

Date.getUTCMilliseconds()方法用于返回当前日期的毫秒部分,由 0 到 999(包括 0 和 999)之间的整数表示,由您的操作系统指定,以 UTC 时间或不含本地偏移量的时间表示。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCMilliseconds();

例子

var dateObject = new Date();            // Create new date object with today's date
alert(dateObject.getUTCMilliseconds()); // Alerts the milliseconds of dateObject

getUTCMinutes()

Date.getUTCMinutes()方法用于返回过去一小时的分钟数,由您的操作系统指定,以 UTC 时间或不含本地时差的时间表示。返回值是 0 到 59 之间的值。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCMinutes();

例子

var dateObject = new Date();       // Create new date object with today's date
alert(dateObject.getUTCMinutes()); // Alerts the UTC minutes of the hour.

getUTCMonth()

Date.getUTCMonth()方法用于返回操作系统指定的一年中的月份,用 UTC 时间或不含本地时差的时间表示。返回值是一个从 0 到 11 的值。UTC 代表协调世界时,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCMonth();

例子

var dateObject = new Date();       // Create new date object with today's date
alert(dateObject.getUTCMonth());   // Alerts the month.

getUTCSeconds()

Date.getUTCSeconds()方法用于返回过去最后一分钟的秒数,该时间取自操作系统指定的时间,以 UTC 时间或不含本地偏移量的时间表示。返回值是 0 到 59 之间的值。UTC 代表世界时间坐标,与格林威治标准时间(GMT)相同。

语法

exampleDate.getUTCSeconds();

例子

var dateObject = new Date();       // Create new date object with today's date
alert(dateObject.getUTCSeconds()); // Alerts the seconds past the minute

解析( )

Date.parse()方法用于返回从给定日期date(见语法)到当前日期的时间,以毫秒为单位。当前日期取自客户端操作系统。指定的完整日期必须采用以下格式:

DayOfWeek, dayOfMonth MM YYYY HH:MM:SS TimeZoneOffset

以上是toGMTString()方法遵循的格式。

语法

exampleDate.parse(date);

例子

alert("The number of milliseconds from January 1st, 1970 to Sun, Jan 3 1999 10:15:30 is : " + Date.parse('Sun, Jan 3 1999 10:15:30') ); // Will alert "The number of milliseconds from January 1st, 1970 to Sun, Jan 3 1999 10:15:30 is : 915387330000"

setDate( )

Date.setDate()方法用于设置Date对象的日期属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

day参数应该在 1 到 31 之间(包括 1 和 31)。如果提供 0,则该月中的某一天属性将设置为上个月的最后一个小时。如果提供-1,则该月中的某一天属性将设置为上个月最后一个小时之前的一个小时。如果一个月有 30 天,提供 32 天会将该月的日期属性设置为下个月的第二天。如果一个月有 31 天,那么提供 32 天会将该月的日期属性设置为下个月的第一天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setDate(day);

例子

var dateObject = new Date(); // Create new date object with today's date
dateObject.setDate(3);       // Changes the day from whatever it currently is to 3 (Wednesday)
alert(dateObject.getDate()); // Alerts 3

setFullYear()

Date.setFullYear()方法用于设置Date对象的 year 属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

此外,通过提供可选的monthday参数,该方法可用于设置Date对象的月和日属性。

year参数应该是用零填充的四位数年份。允许负值。

month参数应该是 0 到 11 之间的整数。如果提供-1,month 属性将设置为上一年的最后一个月。如果提供 12,则 month 属性将设置为下一年的第一个月,如果提供 13,则 month 属性将设置为下一年的第二个月。

day参数应该是 1 到 31 之间的整数。如果您提供 0,日期将设置为上个月的最后一天。如果提供-1,日期将设置为上个月最后一天的前一天。如果一个月有 31 天,则提供 32 天将得到下个月的第一天,如果一个月有 30 天,则提供 32 天将得到下个月的第二天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setFullYear(year, month, day);

例子

var dateObject = new Date();     // Create new date object with today's date
dateObject.setFullYear(1999);    // Set year to 1999
alert(dateObject.getFullYear()); // Alerts 1999.

setHours()

Date.setHours()方法用于设置Date对象的时间属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

此外,通过提供可选的minutessecondsmilliseconds参数,该方法可用于设置Date对象的分、秒和毫秒属性。

hours参数应该是 0 到 23 之间的整数。如果提供 1,hours 属性将设置为前一天的最后一个小时,如果提供 24,hours 属性将设置为第二天的第一个小时。

minutes参数应该是 0 到 59 之间的整数。如果提供 1,分钟属性将设置为前一小时的最后一分钟,如果提供 60,分钟属性将设置为下一小时的第一分钟。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setHours(hour, minutes, seconds, milliseconds);

例子

var dateObject = new Date();     // Create new date object with today's date
dateObject.setHours(11);         // Set the hour to 11am
alert(dateObject.getHours());    // Alerts 11.

setMilliseconds()

Date.setMilliseconds()方法用于设置Date对象的毫秒属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setMilliseconds(milliseconds);

例子

var dateObject = new Date();         // Create new date object with today's date
dateObject.setMilliseconds(300);     // Sets the milliseconds value to 300
alert(dateObject.getMilliseconds()); // Alerts 300

setMinutes()

Date.setMinutes()方法用于设置Date对象的分钟属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。您还可以通过向该方法提供可选的secondsmilliseconds参数来设置Date对象的秒和毫秒。

minutes参数应该是 0 到 59 之间的整数。如果提供 1,分钟属性将设置为前一小时的最后一分钟,如果提供 60,分钟属性将设置为下一小时的第一分钟。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setMinutes(minutes, seconds, milliseconds);

例子

var dateObject = new Date();         // Create new date object with today's date
dateObject.setMinutes(40);           // Sets the minutes value to 40
alert(dateObject.getMinutes());      // Alerts 40

集月()

Date.setMonth()方法用于设置Date对象的月份属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。此外,您可以通过提供可选的day参数来设置Date对象的 day 属性。

month参数应该是 0 到 11 之间的整数。如果提供-1,month 属性将设置为上一年的最后一个月。如果提供 12,则 month 属性将设置为下一年的第一个月,如果提供 13,则 month 属性将设置为下一年的第二个月。

day参数应该是 1 到 31 之间的整数。如果您提供 0,日期将设置为上个月的最后一天。如果提供-1,日期将设置为上个月最后一天的前一天。如果一个月有 31 天,提供 32 天将得到下个月的第一天,如果一个月有 32 天,提供 32 天将得到下个月的第二天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setMonth(month, day);

例子

var dateObject = new Date();    // Create new date object with today's date
dateObject.setMonth(4);         // Sets the month value to 4
alert(dateObject.getMonth());   // Alerts 4

setSeconds()

Date.setSeconds()方法用于设置Date对象的秒属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。此外,通过提供一个可选的milliseconds参数,这个方法可以用来设置Date对象的毫秒属性。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setSeconds(seconds, milliseconds);

例子

var dateObject = new Date();    // Create new date object with today's date
dateObject.setSeconds(11);      // Set seconds to 11
alert(dateObject.getSeconds()); // Alerts 11.

第七个( )

Date.setTime()方法用于设置自 1970 年 1 月 1 日午夜以来的毫秒数。这种方法不会查询系统时钟的日期和时间。

milliseconds参数应该是一个正整数或负整数。然后,Date对象将根据参数计算日、月、年、小时、分钟、秒和毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setTime(milliseconds);

例子

var dateObject = new Date();        // Create new date object with today's date
dateObject.setTime(-8348438943984); // Subtract 83,848,438,943,984 milliseconds from midnight January 1 1970
alert(dateObject.toDateString());   // Alerts "Sat Jun 13 1705"

setUTCDate()

Date.setUTCDate()方法用于根据通用时间设置Date对象的日期属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

day参数应该在 1 到 31 之间。如果提供 0,则该月中的某一天属性将设置为上个月的最后一个小时。如果提供-1,则该月中的某一天属性将设置为上个月最后一小时的前一天。如果一个月有 30 天,提供 32 天会将该月的日期属性设置为下个月的第二天。如果一个月有 31 天,则提供 32 天会将该月的日期属性设置为下个月的第一天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCDate(day);

例子

var dateObject = new Date();        // Create new date object with today's date
dateObject.setUTCDate(3);           // Changes the day from whatever it currently is to 3
alert(dateObject.getUTCDate());     // Alerts 3

setUTCFullYear()

Date.setUTCFullYear()方法用于根据世界时设置Date对象的年份属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

此外,通过提供可选的monthday参数,该方法可用于设置Date对象的月和日属性。

year参数应该是用零填充的四位数年份。允许负值。

month参数应该是 0 到 11 之间的整数。如果提供-1,month 属性将设置为上一年的最后一个月。如果提供 12,则 month 属性将设置为下一年的第一个月,如果提供 13,则 month 属性将设置为下一年的第二个月。

day参数应该是 1 到 31 之间的整数。如果您提供 0,日期将设置为上个月的最后一天。如果提供-1,日期将设置为上个月最后一天的前一天。如果一个月有 31 天,则提供 32 天将得到下个月的第一天,如果一个月有 30 天,则提供 32 天将得到下个月的第二天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCFullYear(year, month, day);

例子

var dateObject = new Date();        // Create new date object with today's date
dateObject.setUTCFullYear(1999);    // Set year to 1999
alert(dateObject.getUTCFullYear()); // Alerts 1999.

setUTCHours()

Date.setUTCHours()方法用于根据通用时间设置Date对象的时间属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

此外,通过提供可选的minutessecondsmilliseconds参数,该方法可用于设置Date对象的分、秒和毫秒属性。

hours参数应该是 0 到 23 之间的整数。如果提供 1,hours 属性将设置为前一天的最后一个小时,如果提供 24,hours 属性将设置为第二天的第一个小时。

minutes参数应该是 0 到 59 之间的整数。如果提供 1,分钟属性将设置为前一小时的最后一分钟,如果提供 60,分钟属性将设置为下一小时的第一分钟。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCHours(hour, miutes, seconds, milliseconds);

例子

var dateObject = new Date();            // Create new date object with today's date
dateObject.setUTCHours(11);             // Set the hour to 11am
alert(dateObject.getUTCHours());        // Alerts 11.

setUTCMilliseconds()

Date.setUTCMilliseconds()方法用于根据通用时间设置Date对象的毫秒属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCMilliseconds(milliseconds);

例子

var dateObject = new Date();            // Create new date object with today's date
dateObject.setUTCMilliseconds(300);     // Sets the milliseconds value to 300
alert(dateObject.getUTCMilliseconds()); // Alerts 300

setUTCMinutes()

Date.setUTCMinutes()方法用于根据通用时间设置Date对象的分钟属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。您还可以通过向该方法提供可选的secondsmilliseconds参数来设置Date对象的秒和毫秒。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

minutes参数应该是 0 到 59 之间的整数。如果提供 1,分钟属性将设置为前一小时的最后一分钟,如果提供 60,分钟属性将设置为下一小时的第一分钟。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCMinutes(minutes, seconds, milliseconds);

例子

var dateObject = new Date();       // Create new date object with today's date
dateObject.setUTCMinutes(40);      // Sets the minutes value to 40
alert(dateObject.getUTCMinutes()); // Alerts 40

setUTCMonth()

Date.setUTCMonth()方法用于根据世界时设置Date对象的月份属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。此外,您可以通过提供可选的day参数来设置Date对象的 day 属性。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

month参数应该是 0 到 11 之间的整数。如果提供-1,month 属性将设置为上一年的最后一个月。如果提供 12,则 month 属性将设置为下一年的第一个月,如果提供 13,则 month 属性将设置为下一年的第二个月。

day参数应该是 1 到 31 之间的整数。如果您提供 0,日期将设置为上个月的最后一天。如果提供-1,日期将设置为上个月最后一天的前一天。如果一个月有 31 天,提供 32 天将得到下个月的第一天,如果一个月有 32 天,提供 32 天将得到下个月的第二天。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCMonth(month, day);

例子

var dateObject = new Date();       // Create new date object with today's date
dateObject.setUTCMonth(4);         // Sets the month value to 4
alert(dateObject.getUTCMonth());   // Alerts 4

setUTCSeconds()

Date.setUTCSeconds()方法用于根据通用时间设置Date对象的秒属性。Date对象将使用这个值进行操作。这种方法不会查询系统时钟的日期和时间。此外,通过提供一个可选的milliseconds参数,这个方法可以用来设置Date对象的毫秒属性。

UTC 代表世界协调时间,由世界时间标准设定。它与格林威治标准时间(GMT)相同。

seconds参数应该是 0 到 59 之间的整数。如果提供 1,seconds 属性将设置为上一分钟的最后一秒,如果提供 60,seconds 属性将设置为下一分钟的第一秒。

milliseconds参数应该是 0 到 999 之间的整数。如果提供 1,毫秒属性将设置为前一秒的最后一毫秒。如果提供 1000,毫秒属性将设置为下一秒的第一毫秒。

该方法返回一个整数,表示从Date对象的新值到 1970 年 1 月 1 日午夜之间的毫秒数。

语法

exampleDate.setUTCSeconds(seconds, milliseconds);

例子

var dateObject = new Date();       // Create new date object with today's date
dateObject.setUTCSeconds(11);      // Set seconds to 11
alert(dateObject.getUTCSeconds()); // Alerts 11.

toDateString()

Date.toDateString()方法返回表示Date对象的日期(不是时间)的格式化字符串。格式是三个字母的日缩写后跟 MMM DD YYYY 例如,“2013 年 1 月 26 日,星期日”。

语法

exampleDate.toDateString();

例子

var dateObject = new Date();       // Create new date object with today's date
alert(dateObject.toDateString());  // Alerts the current date.

toisostring()

Date.toISOString()方法返回一个表示Date对象值的字符串,其格式符合 ISO-8601:YYYY-MM-DDTHH:MM:ss . sssz

语法

exampleDate.toISOString();

例子

var dateObject = new Date();       // Create new date object with today's date
alert(dateObject.toISOString());   // Alerts today's date in ISO-8601 format.

toJSON()

方法将返回一个表示 JSON 格式的日期的字符串。JSON 格式与 ISO 格式相同,所以这个方法与调用Date.toISOString()相同。

语法

exampleDate.toJSON();

例子

var dateObject = new Date(); // Create new date object with today's date
alert(dateObject.toJSON());  // Alerts today's date in ISO-8601 format.

toLocaleDateString()

Date.toLocaleDateString()方法用于返回标准格式的日期,该日期取自操作系统指定的日期,由Date对象使用。该值根据主机浏览器、主机操作系统以及可能的用户设置所指定的区域设置约定进行格式化。因此,该方法在不同的浏览器和不同的操作系统中会有不同的表现

语法

exampleDate.toLocaleDateString();

例子

var dateObject = new Date(); // Create new date object with today's date
alert(dateObject.toLocaleDateString()); // Alerts today's date in a formatted string, e.g. "Thursday, September 13, 2012"

托 LocaleTimeString()

Date.toLocaleTimeString()方法用于以标准格式返回Date对象的时间部分,其信息取自操作系统指定的日期,并由Date对象使用。使用由主机浏览器、主机操作系统以及可能的用户设置指定的区域设置约定返回该值。因此,该方法在不同的浏览器和不同的操作系统中会有不同的表现。

语法

exampleDate.toLocaleTimeString();

例子

var dateObject = new Date();            // Create new date object with today's date
alert(dateObject.toLocaleTimeString()); // Alerts the current time, e.g. "09:17:42"

托洛卡斯汀( )

Date.toLocaleString()方法用于以标准格式返回Date对象的值,其信息取自操作系统指定的日期,并由Date对象使用。使用由主机浏览器、主机操作系统以及可能的用户设置指定的区域设置约定返回该值。因此,该方法在不同的浏览器和不同的操作系统中会有不同的表现。

语法

exampleDate.toLocaleString();

例子

var dateObject = new Date(); // Create new date object with today's date
alert(dateObject.toLocaleString()); // Alerts the current time, e.g. "Thu Sep 13 2012 09:17:42 GMT-0700 (Pacific Daylight Time)"

toString()

Date.toString()方法用于将Date对象转换成字符串。

语法

exampleDate.toString();

例子

var dateObject = new Date(); // Create new date object with today's date
alert(dateObject.toString()); // Alerts the current time, e.g. " Thu Sep 13 2012 09:17:42 GMT-0700 (Pacific Daylight Time)"

toTimeString()

Date.toTimeString()方法用于将Date对象的时间部分转换成字符串。

语法

exampleDate.toTimeString();

例子

var dateObject = new Date();      // Create new date object with today's date
alert(dateObject.toTimeString()); // Alerts the current time, e.g. "09:17:42 GMT-0700 (Pacific Daylight Time)"

toUTCString()

Date.toUTCString()方法用于根据通用协调时间将Date对象转换为字符串。

语法

exampleDate.toUTCString();

例子

var dateObject = new Date();      // Create new date object with today's date
alert(dateObject.toUTCString());  // Alerts the current time, e.g. " Thu Sep 13 2012 16:17:42 GMT"

世界协调时( )

Date对象上的其他方法不同,Date.UTC()方法是为了方便而公开的静态方法。因此,您不必为了访问它而创建一个新的Date对象——事实上,您不能从一个Date对象访问它。相反,你可以直接从全局Date对象中访问它。

Date.UTC()方法采用如下一组参数:

  • Year:四位数年份;1900 年以后的任何一年都有效。必选。
  • Month:0 到 11 之间的整数,表示所需月份。必选。
  • Date:1 到 31 之间的一个整数,表示一个月中的某一天。
  • Hours:0 到 23 之间的整数,表示所需的小时。
  • Min:0 到 59 之间的整数,表示所需的分钟数。
  • Sec:从 0 到 59 的整数,表示所需的秒。
  • MS:0 到 999 之间的整数,表示所需的毫秒数。

该方法将返回一个数字,该数字表示指定日期与 1970 年 1 月 1 日午夜之间的毫秒数。

语法

Date.UTC(Year, Month, Date, Hours, Min, Sec, MS);

例子

var intMilliseconds = Date.UTC(2013,01,26); // intMilliseconds is now 1361836800000
var myNewDate = new Date(intMilliseconds);  // Create a new date object
alert(myNewDate.toUTCString()):             // Alerts "Tue, 26 Feb 2013 00:00:00 GMT".

valueOf()

Date.valueOf()方法返回一个Date对象的原始值,即从 UTC 时间 1970 年 1 月 1 日午夜开始的秒数。

语法

exampleDate.valueOf();

例子

var dateObject = new Date(); // Create new date object with today's date
alert(dateObject.valueOf()); // Alerts the milliseconds from midnight January 1 1970, e.g."1347553875570"

数学

Math对象提供了对各种数学属性和函数的访问。与本章介绍的其他对象不同,Math对象不是一个构造函数。你不需要创建一个新的Math对象来使用它;您可以直接使用它的属性和方法。

数学属性

Math 对象有几个对应于常见数学常数的属性:

  • E:欧拉数
  • LN2:2 的自然对数
  • LN10:10 的自然对数
  • LOG2E:E 的以 2 为底的对数
  • LOG10E:E 的以 10 为底的对数
  • PI:圆周率(π)的值
  • SQRT1_2:1/2 的平方根
  • SQRT2:2 的平方根

语法

Math.E;
Math.LN2;
Math.PI;

例题

alert(Math.E);
alert(Math.LN2);
alert(Math.PI);

数学方法

Math对象有几种方法,包括三角函数、舍入和随机化。

abs()

Math.abs()方法用于计算所提供参数的绝对值。出于计算目的,非数字参数被转换为数字。

语法

Math.abs(number);

例题

alert(Math.abs(-1));             // will alert "1"
alert(Math.abs(0.1));            // will alert "0.1"
alert(Math.abs("Math is fun!")); // will alert "NaN"
alert(Math.abs(null));           // will alert "0"

acos()

Math.acos()方法返回所提供参数的反余弦(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.acos(number);

例题

alert(Math.acos(1));              // will alert 0
alert(Math.acos(-1));             // will alert 3.141592653589793
alert(Math.acos(0.1));            // will alert 1.4706289056333368
alert(Math.acos("Math is fun!")); // will alert NaN
alert(Math.acos(null));           // will alert 1.5707963267948966

阿辛( )

Math.asin()方法返回所提供参数的反正弦(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.asin(number);

例题

alert(Math.asin(1));              // will alert 1\. 5707963267948966
alert(Math.asin(-1));             // will alert -1\. 5707963267948966
alert(Math.asin(0.1));            // will alert 0.1001674211615598
alert(Math.asin("Math is fun!")); // will alert NaN
alert(Math.asin(null));           // will alert 0

atan()

Math.atan()方法返回所提供参数的反正切值(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.atan(number);

例题

alert(Math.atan(1));              // will alert 0.7853981633974483
alert(Math.atan(-1));             // will alert 0.7853981633974483
alert(Math.atan(0.1));            // will alert 0.09966865249116204
alert(Math.atan("Math is fun!")); // will alert NaN
alert(Math.atan(null));           // will alert 0

atan2()

Math.atan2()方法返回其两个参数的商的反正切值。该值以介于-PI/2 和 PI/2 之间的弧度返回。出于计算目的,非数字参数被转换为数字。

语法

Math.atan2(num1, num2);

例题

alert(Math.atan2(1, 7));              // will alert 0.1418970546416394
alert(Math.atan2("Math is fun!", 8)); // will alert NaN
alert(Math.atan2(null, null));        // will alert 0

细胞( )

Math.ceil()方法返回上舍入到下一个最接近整数的参数。出于计算目的,非数字参数被转换为数字。对比Math.floor()

语法

Math.ceil(number);

例题

alert(Math.ceil(0.4));                // will alert 1
alert(Math.ceil(-7.9));               // will alert -7
alert(Math.ceil("Math is fun"));      // will alert NaN
alert(Math.ceil("0.1"));              // will alert 1

cos()

Math.cos()方法返回所提供参数的余弦值(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.cos(number);

例题

alert(Math.cos(1));                   // will alert 0.540323058681398
alert(Math.cos(0.1));                 // will alert 0.9950041652780258
alert(Math.cos("Math is fun!"));      // will alert NaN
alert(Math.cos(null));                // will alert 1

exp()

Math.exp()方法接受一个数字参数并返回 e^number 作为结果。

语法

Math.exp(number);

例子

alert(Math.exp(-1));              // will alert 0.36787944117144233

地板( )

Math.floor()方法返回下一个最接近的整数的参数。出于计算目的,非数字参数被转换为数字。对比Math.ceil()

语法

Math.floor(number);

例题

alert(Math.floor(0.4));           // will alert 0
alert(Math.floor(-7.9));          // will alert -8
alert(Math.floor("Math is fun")); // will alert NaN
alert(Math.floor("0.1"));         // will alert 0

日志( )

Math.log()方法将返回参数的自然对数。非数字参数是为了计算而强制转换的。

语法

Math.log(number);

例题

alert(Math.log(2));               // will alert 0.691347185599453
alert(Math.log("0));              // will alert -Infinity
alert(Math.log(-34));             // Will alert NaN

最大( )

Math.max()方法接受一组数字参数,并将返回其中最大的一个。传递一个非数字参数将导致该方法返回NaN。如果没有给定参数,该方法将返回-Infinity。对比Math.min()

语法

Math.max(num1, num2, ..., numN);

例子

alert(Math.max(5, 0, 2, 100, 4, 68490, 4, -1, 234)); // will alert 68490

最小值( )

方法接受一组数字参数,并将返回其中最小的一个。传递一个非数字参数将导致该方法返回NaN。如果没有给定参数,该方法将返回Infinity。对比Math.max()

语法

Math.min(num1, num2, ..., numN);

例子

alert(Math.min(5, 0, 2, 100, 4, 68490, 4, -1, 234)); // will alert -1

功率( )

Math.pow()方法带两个参数numberBasenumberExponent,返回numberBase^numberExponent。非数字参数是为了计算而强制转换的。

语法

Math.pow(numberBase, numberExponent);

例题

alert(Math.pow(10, 10));                 // will alert 10000000000
alert(Math.pow(100, 0.5));               // will alert 10
alert((Math.pow(2, 0.5) == Math.SQRT2)); // will alert true

随机( )

Math.random()方法将返回一个大于或等于 0 且小于 1 的 16 位小数的浮点数。

语法

Math.random();

例题

alert(Math.random());                    // will alert a random number, such as 0.40920510
// Function to generate a random integer between 0 and intMax
function generateRandomInt(intMax) {
    return Math.floor((Math.random() * intMax) + 1);
}
alert(generateRandomInt(100));           // will alert a random integer between 0 and 100.

圆形( )

Math.round()方法接受一个数字参数,并将该数字四舍五入为最接近的整数。出于计算目的,非数字参数将被强制转换。

语法

Math.round(number);

例题

alert(Math.round(1.49));         // will alert 1
alert(Math.round(1.5));          // will alert 2

罪恶( )

Math.sin()方法返回所提供参数的正弦值(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.sin(number);

例题

alert(Math.sin(1));              // will alert 0.8414709848078965
alert(Math.cos(0.1));            // will alert 0.09983341664682815
alert(Math.cos("Math is fun!")); // will alert NaN
alert(Math.cos(null));           // will alert 1

sqrt()

Math.sqrt()方法接受一个数字参数并返回该数字的平方根。负数将返回NaN,非数字参数将被强制转换用于计算。

语法

Math.sqrt(number);

例子

alert(Math.sqrt(100));           // will alert 10

谭( )

Math.tan()方法返回所提供参数的正切值(以弧度为单位)。出于计算目的,非数字参数被转换为数字。

语法

Math.tan(number);

例题

alert(Math.tan(1));               // will alert 1.5574077246549023
alert(Math.tan(0.1));             // will alert 0.10033467208545055
alert(Math.tan("Math is fun!"));  // will alert NaN
alert(Math.tan(null));            // will alert 0

数字

Number对象是数值的包装类。在 JavaScript 中,所有数值都是 64 位浮点数。

数字属性

JavaScript Number对象有几个在数字比较中有用的属性,特别是因为 JavaScript 是弱类型的:

  • MAX_VALUE:JavaScript 中可能的最大数值
  • MIN_VALUE:JavaScript 中可能的最小数值
  • NEGATIVE_INFINITY:负无穷大
  • NaN:特殊“非数字”值(详见第二章)
  • POSITIVE_INFINITY:正无穷大

语法

Number.MAX_VALUE;
Number.MIN_VALUE;

例子

alert(Number.MAX_VALUE);          // will alert 1.7976931348623157e+308

数字方法

toexponentail_)

Number.toExponential()方法返回一个以指数记数法表示数字的字符串。该方法采用一个介于 0 和 20 之间的可选整数参数,该参数表示小数点后的位数;如果省略,该方法将根据需要使用尽可能多的数字来完全表示该数字。

语法

exampleNumber.toExponential(digits);

例题

var myNumber = 4309;
alert(myNumber.toExponential());  // will alert 4.309e+3
alert(myNumber.toExponential(2)); // will alert 4.31e+3

toFixed( )

Number.toFixed()方法返回一个表示十进制数的字符串,并且在可选整数参数指定的小数点后有精确的位数。如果未指定该参数,则该参数被视为 0,并且该数字将被四舍五入为最接近的整数。

语法

exampleNumber.toFixed(places);

例题

var myNumber = 40.29;
alert(myNumber.toFixed());       // will alert 40
alert(myNumber.toFixed(1));      // will alert 40.3
alert(myNumber.toFixed(4));      // will alert 40.2900

最高精度( )

Number.toPrecision()方法返回一个字符串,表示四舍五入到参数指定的有效位数的指定数字。根据需要,结果可以是定点或指数表示法。通常,该参数应该是 1 到 21 之间的一个整数值,尽管这可以根据实现而变化。超出允许范围的参数将引发范围错误。如果没有指定数字参数,该方法只返回数字的字符串表示,相当于调用toString()方法。

语法

exampleNumber.toPrecision(precision);

例题

var myNumber = 40.29;
alert(myNumber.toPrecision());   // alerts 40.29
alert(myNumber.toPrecision(1));  // alerts 4e+1 (which is 40 in exponential notation)
alert(myNumber.toPrecision(10)); // alerts 40.2900000000

toString()

Number.toString()方法返回一个表示数字值的字符串。该方法采用一个可选参数,该参数是一个介于 2 和 26 之间的整数,表示字符串的基数。如果您提供的参数超出了可接受的范围,将会引发异常。如果您根本没有提供基数,则默认值为 10。

语法

exampleNumber.toString(radix);

例题

var myNumber = 17;
alert(myNumber.toString());      // alerts 17
alert(myNumber.toString(2));     // alerts 10001

valueOf()

Number.valueOf()方法将数字的原始值作为数字数据类型返回。这种方法不常用,因为直接赋值是首选。

语法

exampleNumber.valueOf();

例题

var myNumber = 17;
var myOtherNumber = myNumber.valueOf();
var myBetterWay = myNumber;                       // direct assignment
alert(myOtherNumber === myBetterWay);             // Will alert true, because the two are the same

正则表达式

JavaScript RegExp 对象提供了 JavaScript 中正则表达式的实现。正则表达式是搜索和操作文本字符串的强大工具,有自己的语言和方法。本参考资料仅涵盖正则表达式的 JavaScript 实现,并不深入研究如何实际构建它们。

在 JavaScript 中,正则表达式以两种方式之一创建:通过RegExp对象构造函数,或者通过文字。使用构造函数时,表达式中出现的任何字符串都必须进行转义。

语法

var exampleRegExp = new RegExp(regularExpression);
var exampleRegExp = regularExpression;

例题

var myConstructedRegExp = new RegExp("the", "g"); // same as myLiteralRegExp
var myLiteralRegExp = /the/g;                     // search an entire string for "the"

正则表达式属性

正则表达式有几个属性(全局、不区分大小写等。)并且RegExp对象对它们都有匹配的属性。

全球的

RegExp.global属性是一个布尔值,如果已经为正则表达式设置了global标志,则该布尔值被设置为真。

语法

exampleRegExp.global;

例子

var myRegExp = /the/g;
alert(myRegExp.global);     // will alert true

ignoreCase

RegExp.ignoreCase属性是一个布尔值,指示是否为正则表达式设置了忽略大小写标志。

语法

exampleRegExp.ignoreCase;

例子

var myRegExp = /the/i;
alert(myRegExp.ignoreCase); // will alert true

loadIndex

RegExp.lastIndex属性将包含一个整数,表示由RegExp.match()方法或RegExp.test()方法找到的最后一个匹配后的字符位置。仅当全局属性设置为 true 时,才会设置此属性。

语法

exampleRegExp.lastIndex;

例子

var slogan = "Never give up, never surrender!";
var regExp = /never/gi;
while (regExp.test(slogan) === true) {
    alert("Found 'never'; index is now " + regExp.lastIndex);
}

多线

RegExp.multiline属性是一个布尔值,指示是否在正则表达式上设置了多行标志。

语法

exampleRegExp.multiline;

例子

var myRegExp = /never/m;
alert(myRegExp.multiline);  // will alert true

来源

RegExp.source属性包含一个表示正则表达式本身的字符串。

语法

exampleRegExp.source;

例子

var myRegExp = /never/g;
alert(myRegExp.source); // will alert "/never/g" (some browsers will just alert "never" which is equivalent)

正则表达式方法

RegExp对象方法用于在目标上运行正则表达式。

执行( )

RegExp.exec()方法将目标字符串作为参数,并对其运行正则表达式匹配。如果没有找到匹配,该方法返回 null。如果找到匹配项,该方法将停止并返回具有以下属性的数组:

  • 数组中的第一个元素是匹配的文本。
  • 数组中的后续元素是正则表达式中任何匹配括号的内容。
  • 该数组将有一个包含目标字符串的input属性。
  • 该数组将有一个index属性,该属性将包含一个表示匹配子字符串索引的整数。

此外,该方法将更新RegExp对象的lastIndex

如果正则表达式设置了global标志,那么对match()方法的后续调用将继续对字符串进行扫描,返回找到的任何匹配,直到没有匹配为止。

由于迭代的性质,RegExp.exec()通常在循环中使用。

语法

exampleRegExp.exec(target)

例题

var regExp = /never/gi;     // global case-insensitive search for "never"
var slogan = "Never give up, never surrender!";
alert(regExp.exec(slogan)); // will alert "Never"
alert(regExp.exec(slogan)); // will alert "never"
alert(regExp.exec(slogan)); // will alert null

// Demonstrate using a loop: this will alert "Never" and then "never".
var regExp = /never/gi,
      slogan = "Never give up, never surrender!",
      result;
while(result = regExp.exec(slogan)) {
    alert(result);
}

测试( )

RegExp.test()方法将目标字符串作为参数,并在目标字符串上运行正则表达式匹配。如果匹配,则该方法返回 true 否则返回 false。

语法

exampleRegExp.test(target);

例题

var regExp = /never/g;
var slogan = "Never give up, never surrender!";
var otherSlogan = "May the force be with you!";
alert(regExp.test(slogan));      // will alert true
alert(regExp.test(otherSlogan)); // will alert false

线

对象是所有字符串的包装类。每当您访问字符串文字上的String的属性或方法之一时,JavaScript 将在幕后用一个String对象包装该文字,为您提供您所请求的功能。您的文字字符串将保持不变,但看起来拥有一个String对象的所有属性和方法。

很少直接使用String对象;你几乎不会调用使用String作为构造函数来创建一个String对象。创建一个String对象的唯一好处是,因为结果是一个对象,你可以给它其他的属性或方法。

如果需要使用String构造函数创建一个String对象,语法很简单,结果是一个包含所有字符串属性和方法的对象。要访问用于构造对象的实际字符串,请使用valueOf()方法。

语法

var exampleString = new String("desired string");

例题

var myConstructedString = new String("Hi");
var myLiteralString = "Hi";
alert(myConstructedString === myLiteralString);           // will alert false, because literals and objects are different types.
alert(myConstructedString == myLiteralString);            // will alert true, because JavaScript uses the valueOf method in cast comparisons.
alert(myConstructedString.valueOf() === myLiteralString); // will alert true.

弹簧属性

JavaScript 全局String 对象有一些属性,其中大部分是从Object继承的。它为自己定义的唯一属性是length

长度

String.length属性包含一个表示字符串中字符总数的整数。

语法

exampleString.length;

例子

var myString = "Hi";
alert(myString.length);        // will alert 2

字符串方法

JavaScript 提供了几种非常有用的操作字符串的方法,包括转换成数组和正则表达式扫描。

夏拉特( )

String.charAt()方法期望一个整数作为参数,表示字符串中的一个索引,并将返回出现在该索引处的字符。字符串中的字符从左到右从零开始索引。如果指定的索引超出了字符串的长度,该方法将返回一个空字符串。

语法

exampleString.charAt(index);

例子

var myString = "Hello World";
alert(myString.charAt(6));     // will alert "W"--spaces are characters too!

charCodeAt()

String.charCodeAt()方法期望一个整数作为参数,表示字符串中的一个索引,并将返回该索引处字符的 Unicode 数值。字符串中的字符从左到右从零开始索引。如果指定的索引超出了字符串的长度,该方法将返回一个空字符串。

语法

exampleString.charCodeAt(index);

例子

var myString = "Hello World";
alert(myString.charCodeAt(6)); // will alert "87"

concat()

String.concat()方法组合一个或多个字符串(作为参数提供)并返回结果。原始字符串不会改变。

语法

exampleString.concat(string1, string2, ..., stringN);

例子

var myString = "Hello";
var myOtherString = "World";
var mySpace = " ";
var myFullMessage = myString.concat(mySpace, myOtherString, "!");
alert(myFullMessage)               // will alert Hello World!

fromCharCode()

String.fromCharCode()方法将任意数量的 Unicode 字符代码作为参数。它将代码转换成相关的字符,并返回结果字符串。

注意这是String对象的静态方法,所以可以直接调用;您不需要首先创建一个String对象。

语法

exampleString.fromCharCode(charCode1, charCode2, ..., charCodeN);

例子

alert(String.fromCharCode(87));    // will alert W

索引()

String.indexOf()方法 将一个子串作为参数,从该子串的开头开始搜索。如果找到,该方法返回第一个匹配项的第一个字符的索引;否则,它返回 1。

该方法还可以采用一个可选的整数参数来指定搜索的起始索引。如果未指定,默认值为 0。如果指定的索引超出了字符串的界限,该方法将返回 1。

语法

exampleString.indexOf(substring, startIndex);

例题

var myString = "Never give up, never surrender!";
alert(myString.indexOf("up"));     // will alert 11
alert(myString.indexOf("up", 12)); // will alert -1

lastIndexOf()

String.lastIndexOf()方法将一个子串作为参数,并从末尾开始搜索该子串。如果找到子串,该方法返回索引;否则,它返回 1。

该方法还可以采用一个可选的整数参数来指定起始索引。如果未指定索引,则该方法默认为字符串的长度。

语法

exampleString.lastIndexOf(substring, startIndex);

例子

var myString = "Never give up, never surrender!";
alert(myString.lastIndexOf("er"); // will alert 28.

匹配( )

String.match()方法将正则表达式对象作为参数,然后在字符串上运行该正则表达式。该方法返回一个匹配数组;如果没有设置全局标志,那么只返回第一个匹配。如果不匹配,该方法返回 null。

语法

exampleString.match(regexp);

例题

var regExp = /never/gi,
      slogan = "Never give up, never surrender!",
      otherSlogan = "May the force be with you!";
alert(slogan.match(regExp));      // will alert "Never, never"
alert(otherSlogan.match(regExp)); // will alert "null"

替换( )

JavaScript String.replace()方法提供了一种方法来搜索给定模式的字符串,并用给定的子字符串替换它。搜索参数可以是正则表达式或字符串,替换可以是字符串或函数。方法返回修改后的字符串,原始字符串和参数字符串不变。

如果您提供一个函数作为替换参数,该函数将在每次匹配时执行。匹配的子字符串将被函数的输出替换。该功能将按顺序提供以下参数:

  • match:匹配的子串
  • paren1, paren2, ..., parenN:正则表达式中任何匹配括号匹配的子字符串(如果有)
  • offset:匹配的子串在字符串中的索引
  • string:被搜索的字符串

函数可以作为命名函数或内联函数提供。

语法

exampleString.replace(searchParam, replaceParam);

例题

// Simple find and replace
var slogan = "May the force be with you!";
var newSlogan = slogan.replace("force", "Force"); // newSlogan is now "May the Force be with you!"

// Using a regular expression to search and a function to replace
var slogan = "Never give up, never surrender!",
      regExp = /never/gi,
      newSlogan;
function sarrisify(matchedString) {
    if (matchedString === "Never") {
        return "Always";
    }
    if (matchedString === "never") {
        return "always";
    }
}
newSlogan = slogan.replace(regExp, sarrisify);    // newSlogan is now "Always give up, always surrender!"

搜索( )

String.search()方法将子字符串搜索的正则表达式作为参数,并在字符串上执行搜索。如果找到子字符串,该方法将返回一个整数,该整数表示子字符串第一次出现的起始位置的索引。如果找不到子字符串,该方法返回 1。如果您提供了一个不是正则表达式的参数,JavaScript 将尝试对它进行强制转换,就像您使用RegExp构造函数创建它一样。(有关创建正则表达式的解释,请参见“RegExp”一节。)

语法

exampleString.search(regexp);

例子

var slogan = "Never give up, never surrender!",
      regexp = /up/i;
alert(slogan.search(regexp));                     // will alert 11

切片( )

String.slice()方法提供了一种基于字符索引从更大的字符串中提取子字符串的方法。该方法采用两个参数:

  • startIndex:表示子串起始索引的整数。允许负整数,表示从字符串末尾开始计数的索引。
  • endIndex:表示子串结束索引的整数。该参数是可选的;如果省略,该方法将提取到目标字符串的末尾。允许负整数,表示从字符串末尾开始的索引。请注意,该索引处的字符是返回的切片中包含的而不是

方法返回指定的子字符串。目标字符串不变。对比String.substr()

语法

exampleString.slice(startIndex, endIndex);

例子

var slogan = "Never give up, never surrender!";
var mySlice = slogan.slice(1, 5); // mySlice is now "ever"

拆分( )

String.split()方法提供了一种将字符串转换成数组的方法。该方法将表示分隔符的字符串作为参数。该方法搜索整个目标字符串,并沿着分隔符(不包括在新子字符串中)的每个出现处对其进行拆分。然后将子字符串按顺序放入一个数组中,这就是该方法返回的内容。如果没有提供分隔符,则整个字符串作为数组中的第一个元素返回。

该方法还带有一个可选的limit参数,它是一个整数,表示返回数组中元素的最大数量。如果省略参数,则返回所有元素。

目标字符串不会改变。

语法

exampleString.split(delimiter, limit);

例子

var slogan = "Never give up, never surrender!";
var arrWords = slogan.split(" "); // split the slogan along the spaces, resulting in the array ["Never", "give", "up,", "never", "surrender!"]

substr()

String.substr()方法提供了一种基于起始索引和长度从更大的字符串中提取子字符串的方法。该方法有两个参数:startIndex,它是一个表示子串开始的整数,和length,它是一个表示新的子串的期望长度的整数。

startIndex参数可以是正整数或负整数,也可以是 0。如果是正整数,表示从字符串开始的索引;如果是负整数,则表示从字符串末尾开始的索引。

如果省略了length参数,该方法将返回从指定的起始索引开始的子字符串,一直到目标字符串的末尾。如果length参数指定的子字符串比目标字符串中可用的子字符串长,该方法将返回到目标字符串末尾的子字符串。

语法

exampleString.substr(startIndex, length);

例题

var slogan = "Never give up, never surrender!";
var subString = slogan.substr(15, 5);     // subString is now "never"
var newSlogan = slogan.substr(15);        // newSlogan is now "never surrender!"

子字符串( )

String.substring()方法提供了一种基于字符索引从更大的字符串中提取子字符串的方法。该方法采用两个参数:

  • startIndex:表示子串起始索引的整数。不允许使用负整数,这将导致该方法返回空字符串。
  • endIndex:表示子串结束索引的整数。该参数是可选的;如果省略,该方法将提取到目标字符串的末尾。允许负整数,表示从字符串末尾开始的索引。请注意,此索引处的字符不包括在返回的子字符串中。

方法返回指定的子字符串。目标字符串不变。对比String.slice()

语法

exampleString.substring(startIndex, endIndex);

例子

var slogan = "Never give up, never surrender!";
var mySubstring = slogan.substring(1, 5); // mySubstring is now "ever"

toLowerCase()

String.toLowerCase()方法返回所有字符都转换成小写的目标字符串。目标字符串本身不受影响。

语法

exampleString.toLowerCase();

例子

var slogan = "Never give up, never surrender!";
alert(slogan.toLowerCase());              // will alert "never give up, never surrender!"

toUpperCase()

String.toUpperCase()方法返回所有字符都转换成大写的目标字符串。目标字符串本身不受影响。

语法

exampleString.toUpperCase();

例子

var slogan = "Never give up, never surrender!";
alert(slogan.toUpperCase()); // will alert "NEVER GIVE UP, NEVER SURRENDER!"

修剪( )

String.trim()方法返回删除了所有前导和尾随空格的目标字符串。原始目标字符串不变。

语法

exampleString.trim();

例子

var myString = "   hello world   ";
alert(myString.trim());      // will alert "hello world"

trimLeft()

String.trimLeft()方法返回删除了所有前导空格的目标字符串。原始目标字符串不变。

语法

exampleString.trimLeft ();

例子

var myString = "   hello world   ";
alert(myString.trimLeft());  // will alert "hello world   "

trimRight()

String.trimRight()方法返回删除了所有尾随空格的目标字符串。原始目标字符串不变。

语法

exampleString.trimRight();

例子

var myString = "   hello world   ";
alert(myString.trimRight()); // will alert "   hello world"

杂项全局变量和函数

本节涵盖了 JavaScript 全局范围内存在的各种变量和函数。其中许多并不知名,但可能非常有用。

变量

JavaScript 在全局范围内提供了一些重要的变量。

无穷大

Infinity是代表无穷大的数字。这个和Number.POSITIVE_INFINITY没什么区别。

语法

Infinity

例子

alert(Infinity == Number.POSITIVE_INFINITY); // will alert true

数据

JSON 是一个全局对象,它收集了创建和读取 JSON 格式数据的相关方法。这里就不详细介绍 JSON 了;有关 JSON 的更多信息,请参见www.json.org

JSON.parse()

JSON.parse()方法解析一个 JSON 字符串,然后重新创建并返回它所代表的对象。该方法接受一个 JSON 字符串参数。如果字符串没有解析为有效的 JSON,该方法将抛出语法错误异常。

该方法还采用一个可选的转换函数。transformation 函数提供了一种检查 JSON 键/值对的方法,并在需要时提供不同的值。该函数有两个参数,keyvalue,并且只返回一个值,该值将被用作JSON对象中的值。如果函数返回undefined或者什么都不返回,那么这个键就会从 JSON 对象中删除。

请注意,将按顺序对对象中的每个键/值对调用转换函数。然后,一旦处理完所有的键/值对,就再次调用翻译函数,并给出空字符串作为键和重构的对象本身。此时,您可以进一步修改对象,或者按原样返回(如果您没有正确处理最后一步,翻译将会失败)。

翻译函数有时用于将值从字符串转换为对象——例如,如果一个值是一个格式类似于日期的字符串,翻译器实际上可以基于该字符串创建一个Date对象并返回它。当以这种方式使用时,该函数有时被称为 reviver

语法

JSON.parse(jsonString, translator);

例题

var myJsonString = '{"one" : 1, "two" : 2, "three" : 3}';
myObject = JSON.parse(myJsonString);
alert(myObject.one);                  // will alert 1

function myNumeralTranslator(key, value) {
    if (key === "one") {
        return "I";
    } else if (key === "two") {
        return "II";
    } else if (key === "three") {
        return "III"
    } else {
        return value;
    }
}
myNumeralObject = JSON.parse(myJsonString, myNumeralTranslator);
alert(myNumeralObject.two);           // Will alert "II"

在这个例子中,我们创建了一个简单的 JSON 格式的字符串,包含三个键/值对。首先,我们将它还原为一个对象,然后我们创建一个转换函数,将整数转换为罗马数字,然后我们使用它将相同的字符串还原为不同的对象。

var purchaseJsonString = '{"type" : "gift", "method" : "cash", "date" : "2013-01-28T05:08:11.873Z"}';
function revivePurchase(key, value) {
    if (key === "date") {
        return new Date(value);
    } else {
        return value;
    }
}
var myPurchase = JSON.parse(purchaseJsonString, revivePurchase);
alert(myPurchase.method);             // will alert "cash";
alert(myPurchase.date.toUTCString()); // will alert "Mon, 28 Jan 2013 :05:08:11 GMT"

在本例中,我们创建了一个 JSON 格式的字符串,其中包含一些购买信息,包括一个包含日期格式字符串的值。然后,我们构建一个简单的 reviver 函数来查找日期,并用该值创建一个新的Date对象。

JSON.stringify()

JSON.stringify()方法将一个对象作为参数,并返回相应的 JSON 字符串。

该方法还可以接受一个可选的filter参数,该参数可以用来过滤 JSON 字符串中包含的键/值对。参数可以是数组或函数。

如果筛选器参数是一个数组,那么成员应该表示将包含在字符串中的键。不在过滤器数组中的键不会包含在 JSON 字符串中。

如果filter是一个函数,它将被作为参数传递键和值,并且应该返回该键的期望值。如果返回值是undefined或者什么都没有,那么这个键就不包含在 JSON 字符串中。

语法

JSON.stringify(object, filter);

例题

var myObject  = {"a" : 1, "b" : 2, "foo" : "bar"},
     arrFilter = ["a", "foo"];
function myFilter(key, value) {
    if (key === "a") {
        return undefined;
    } else {
        return value;
    }
}

var firstString = JSON.stringify(myObject ); // stringifies entire object
var secondString = JSON.stringify(myObject, arrFilter);         // Leaves out "b", only stringifies "a" and "foo"
var thirdString = JSON.stringify(myObject, myFilter);           // leaves out "a", only stringifies "b" and "foo"
alert(firstString + "\n" + secondString + "\n" + thirdString);  // Compare all three results.

NaN属性是 JavaScript 中特殊的“非数字”属性。这个属性只在 JavaScript 内部使用,不应该在比较中使用。要确定某个东西是否是NaN,使用在接下来的“函数”一节中讨论的isNaN()方法。

未定义的

undefined属性是 JavaScript 中 undefined 的原始值。以下事情被认为是undefined:

  • 任何已定义但未赋值的变量
  • 试图计算这种未定义变量的语句
  • 没有显式返回值的函数(通过不使用return关键字或通过逻辑)

参见第二章对undefined的深入讨论,以及如何确定事物在 JavaScript 中是否未定义。

请注意,在 JavaScript 的早期实现中,该属性是可写的,允许脚本覆盖该值。在 ECMAScript 5 标准(对应于 JavaScript 1.8.5)中,该属性是只读的。覆盖如此重要的值被认为是不好的做法。

功能

JavaScript 还在全局范围内提供了几个方便的函数。

decorator()、encore()、decorator component()、encore component()

这些方法为编码和解码整个 URIs 及其单个组件(例如,查询字符串)提供了便利的例程。

编码方法不编码字母数字字符或字符- _。!“* ”(和)。另外,encodeURI()方法不会对保留字符进行编码;, / ?:@ & = + $和#。所有其他字符将被替换为一个、两个、三个或四个转义序列,表示该字符的 UTF-8 编码。

语法

decodeURI(encodedURI);
encodeURI(unencodedURI);
decodeURIComponent(encodedURI);
encodeURIComponent(unencodedURI);

例子

var myURI = ' http://www.apress.com/?foo=bar&a="something new"';
alert(encodeURI(myURI)); // will alert http://www.apress.com?foo=bar&a=%22something%20new%22

eval()

eval()方法接受一个字符串参数,并将其解析为 JavaScript。该字符串可以包含对存在于调用eval()的作用域中的对象的引用。

有关 eval 及其注意事项和替代方案的深入讨论,请参见第二章。

语法

eval(target);

例子

var myString = "10 + 2";
var myResult = eval(myString);
alert(myResult);         // will alert 12

isFinite()

isFinite()方法检查参数,如果它是一个有限的数,则返回 true,否则返回 false。这是一个方便的例行检查有限的数字,而不是使用等式。

注意:如果参数是NaN,该方法也会返回 false。

语法

isFinite(target);

例题

alert(isFinite(243988));                   // will alert true
alert(isFinite(Number.NEGATIVE_INFINITY)); // will alert false

isNaN( )

isNaN()方法检查参数,如果是NaN则返回 true,否则返回 false。

实际上,这个方法首先将参数强制为一个数值,如果它还不是一个数值的话。然后它检查结果数值是否等于NaN。这种行为偶尔会让 JavaScript 新手出错,他们认为该方法可以用来确定某个东西是否是数值。

语法

isNaN(target);

例题

alert(isNaN(10));   // will alert false
alert(isNaN("10")); // will alert false even though strings are not numbers; "10" coerces to 10 which is not equal to NaN
alert(isNaN(""));   // will alert false
alert(isNaN(NaN));  // will alert true

解析浮点( )

parseFloat()方法解析提供的参数并试图返回包含在字符串开头的十进制数值。基本上,该方法从字符串的开头开始并构建数字。如果遇到不是数字、指数、小数点或符号(+或-)的字符,该方法将停止并返回它已经创建的任何数字。如果字符串的第一个字符不能转换成数字(空格除外),该方法返回NaN

语法

parseFloat(target);

例题

var myString = "This will return NaN",
    mySecondString = "10.27 this will return 10.27",
    myThirdString = "Even though this has 10.27 in it, it will return NaN",
    myFourthString = "10.27 50.20 this will return only the first number, 10.27";
alert(parseFloat(myString) + "\n" + parseFloat(mySecondString) + "\n" + parseFloat(myThirdString) + "\n" + parseFloat(myFourthString));

parseInt()

parseInt()方法解析参数并返回包含在字符串开头的数字整数值。方法从字符串的开头开始,并生成数字。如果遇到不是数字、指数、小数点或符号(+或–)的字符,该方法将停止并返回已创建的数字。如果字符串的第一个字符不能转换成数字(空格除外),这个方法将返回NaN

语法

parseInt(target);

例题

var myString = "This will return NaN",
    mySecondString = "10.97 this will return 10",
    myThirdString = "Even though this has 10.27 in it, it will return NaN",
    myFourthString = "10.97 50.20 this will return only the first number, 10";
alert(parseInt(myString) + "\n" + parseInt(mySecondString) + "\n" + parseInt(myThirdString) + "\n" + parseInt(myFourthString));

摘要

在本章中,我们已经介绍了几个全局对象的属性和方法以及它们的使用方法:

  • 您可以使用文字符号或使用Array对象作为构造函数来创建数组。
  • JavaScript 会在需要时将字符串和布尔文字与其关联的对象进行静默包装。
  • 您可以使用相关的全局对象作为构造函数来创建字符串和布尔值,但几乎没有必要这样做。
  • Date对象提供了大量用于操作日期的属性和方法。
  • JavaScript 通过它的RegExp全局对象拥有正则表达式的全功能实现。
  • Math对象提供了许多与数学相关的静态属性和方法。

此外,我们还介绍了其他几个全局函数和变量,包括:JSON 对象,它提供了创建和操作 JSON 序列化的功能。

在下一章中,我们将为 JavaScript 中所有可用的控制语句提供类似的参考,并提供它们的用法示例。