BOM:
The navigator object, which provides detailed information about the browser
The location object, which gives detailed information about the page loaded in the browser
The screen object, which gives detailed information about the user ’ s screen resolutionva
Javascript:
< script type="text/javascript" defer="defer" src="example1.js" > < /script >[IE]
The purpose of defer is to indicate that a script won ’ t be changing the structure of the page as it executes.
Type:
var message;
alert(message == undefined); //true
The Null type is the second data type that has only one value: the special value null . Logically, a null
value is an empty object pointer, which is why typeof returns “object” when it ’ s passed a null value
in the following example:
var car = null;
alert(typeof car); //”object”
The value undefined is a derivative of null , so ECMA - 262 defines them to be superficially equal as follows:
alert(null == undefined); //true
For instance, adding 0.1 and 0.2 yields 0.30000000000000004 instead of 0.3. These
small rounding errors make it difficult to test for specific floating - point values. Consider this example:
if (a + b == 0.3){ //avoid!
alert(“You got 0.3.”);
}
Range:
var result = Number.MAX_VALUE + Number.MAX_VALUE;
alert(isFinite(result)); //false
NaN(Not a Number):
Number Conversions:
Number(): used every where
parseInt():for string
parseFloat():fro string
Literal Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash (\)
\' Single quote ( ‘ ) — used when the string is delineated by single quotes.
Example: ‘ He said, \’hey.\’’ .
\” Double quote ( “ ) – used when the string is delineated by double quotes.
Example: “ He said, \”hey.\”” .
\xnn A character represented by hexadecimal code nn (where n is an octal digit 0 - F).
Example: \x41 is equivalent to “A” .
\unnnn A Unicode character represented by the hexadecimal code nnnn (where n is a
hexadecimal digit 0 - F). Example: \u03a3 is equivalent to the Greek character .
var num = 10;
alert(num.toString()); //”10”
alert(num.toString(2)); //”1010”
alert(num.toString(8)); //”12”
alert(num.toString(10)); //”10”
alert(num.toString(16)); //”a”
The String() function follows these rules:
If the value has a toString() method, it is called (with no arguments) and the result is
returned.
If the value is null , “null” is returned.
If the value is undefined , “undefined” is returned.
typeof operator:
The best way to determine if a variable is a primitive type.
instanceof operator:
alert(person instanceof Object); //is the variable person an Object?
alert(colors instanceof Array); //is the variable colors an Array?
alert(pattern instanceof RegExp); //is the variable pattern a RegExp?
No Block - Level Scopes
JavaScript ’ s lack of block - level scopes is a common source of confusion. In other C - like languages, code
blocks enclosed by brackets have their own scope (more accurately described as their own execution
context in ECMAScript), allowing conditional definition of variables. For example, the following code
may not act as expected:
if (true) {
var color = “blue”;
}
alert(color); //”blue”
Here, the variable color is defined inside an if statement. In languages such as C, C++, and Java, that
variable would be destroyed after the if statement is executed. In JavaScript, however, the variable
declaration adds a variable into the current execution context (the global context, in this case). This is
important to keep in mind when dealing with the for statement, which is typically written like this:
for (var i=0; i < 10; i++){
doSomething(i);
}
alert(i); //10
In languages with block - level scoping, the initialization part of the for statement defines variables that
exist only within the context of the loop. In JavaScript, the i variable is created by the for statement and
continues to exist outside the loop after the statement executes.
Variable Declaration:
When a variable is declared using var , it is automatically added to the most immediate context
available. In a function, the most immediate one is the function ’ s local context; in a with statement, the
most immediate is the function context. If a variable is initialized without first being declared, it gets
added to the global context automatically, as in this example:
function add(num1, num2) {
var sum = num1 + num2;
return sum;
}
var result = add(10, 20); //30
alert(sum); //causes an error since sum is not a valid variable
function add(num1, num2) {
sum = num1 + num2;
return sum;
}
var result = add(10, 20); //30
alert(sum); //30
The typeof operator determines a value ’ s primitive type, whereas the instanceof operator is
used to determine the reference type of a value.
Array:(哈哈 这个转换可能将来很有用哦 而且相当方便)
var colors = [“red”, “blue”, “green”]; //creates an array with three strings
alert(colors.toString()); //red,blue,green
alert(colors.valueOf()); //red,blue,green
alert(colors); //red,blue,green
join():(嘿嘿 很有用的哦)
var colors = [“red”, “green”, “blue”];
alert(colors.join(“,”)); //red,green,blue
alert(colors.join(“||”)); //red||green||blue
push() and pop() [L I FO]也很给力 :)
var colors = new Array(); //create an array
var count = colors.push(“red”, “green”); //push two items
count = colors.push(“black”); //push another item on
alert(count); //3
var item = colors.pop(); //get the last item
alert(item); //”black”
alert(colors.length); //2
push() and shift() and unshift() [FIFO] :)
var colors = new Array(); //create an array
var count = colors.push(“red”, “green”); //push two items
alert(count); //2
count = colors.push(“black”); //push another item on
alert(count); //3
var item = colors.shift(); //get the first item
alert(item); //”red”
alert(colors.length); //2
reverse():
var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); //5,4,3,2,1
sort():用于字母排序
改良成数组排序
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //0,1,5,10,15
concat():
var colors = [“red”, “green”, “blue”];
var colors2 = colors.concat(“yellow”, [“black”, “brown”]);
alert(colors); //red,green,blue
alert(colors2); //red,green,blue,yellow,black,brown
slice():The slice() method may accept one or two arguments: the starting and stopping positions of the
items to return.
var colors = [“red”, “green”, “blue”, “yellow”, “purple”];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2); //green,blue,yellow,purple
alert(colors3); //green,blue,yellow
splice():牛掰
var colors = [“red”, “green”, “blue”];
var removed = colors.splice(0,1); //remove the first item
alert(colors); //green,blue
alert(removed); //red - one item array
removed = colors.splice(1, 0, “yellow”, “orange”); //insert two items at position 1
alert(colors); //green,yellow,orange,blue
alert(removed); //empty array
removed = colors.splice(1, 1, “red”, “purple”); //insert two values, remove one
alert(colors); //green,red,purple,orange,blue
alert(removed); //yellow - one item array
Date():
var now = new Date();
- month/date/year (such as 6/13/2004)
- month_name date, year (such as January 12, 2004)
- day_of_week month_name date year hours:minutes:seconds time_zone (such as Tue May 25
2004 00:00:00 GMT - 0700)
var someDate = new Date(Date.parse(“May 25, 2004”));
var someDate = new Date(Date.parse("6/26/2010"))
//May 5, 2005 at 5:55:55 PM GMT
var allFives = new Date(Date.UTC(2005, 4, 5, 17, 55, 55));
Date - Formatting Methods:
toDateString() — Displays the date ’ s day of the week, month, day of the month, and year in
an implementation - specific format
toTimeString() — Displays the date ’ s hours, minutes, seconds, and time zone in an
implementation - specific format
toLocaleDateString() — Displays the date ’ s day of the week, month, day of the month, and
year in an implementation - and locale - specific format
toLocaleTimeString() — Displays the date ’ s hours, minutes, and seconds in an
implementation - specific format
toUTCString() — Displays the complete UTC date in an implementation - specific format
Date/Time Component Methods:
getTime()
setTime( milliseconds )
getFullYear()
getUTCFullYear()
setFullYear( year )
setUTCFullYear( year )
getMonth()
getUTCMonth()
setMonth( month )
setUTCMonth( month )
getDate()
getUTCDate()
setDate( date )
setUTCDate( date )
getDay()
getUTCDay()
getHours()
getUTCHours()
setHours( hours )
setUTCHours( hours )
getMinutes()
getUTCMinutes()
setMinutes( minutes )
setUTCMinutes( minutes )
getSeconds()
getUTCSeconds()
setSeconds( seconds )
setUTCSeconds( seconds )
getMilliseconds()
getUTCMilliseconds()
setMilliseconds( milliseconds )
setUTCMilliseconds( milliseconds )
getTimezoneOffset()
The RegExp Type:
var expression = / pattern / flags ;
/*
* Match all instances of “at” in a string.
*/
var pattern1 = /at/g;
/*
* Match the first instance of “bat” or “cat”, regardless of case.
*/
var pattern2 = /[bc]at/i;
/*
* Match all three-character combinations ending with “at”, regardless of case.
*/
var pattern3 = /.at/gi;
/*
* Match the first instance of “bat” or “cat”, regardless of case.
*/
var pattern1 = /[bc]at/i;
/*
* Same as pattern1, just using the constructor.
*/
var pattern2 = new RegExp(“[bc]at”, “i”);
var text = “cat, bat, sat, fat”;
var pattern1 = /.at/;
var matches = pattern1.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern1.lastIndex); //0
var pattern2 = /.at/g;
var matches = pattern2.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern2.lastIndex); //0
matches = pattern2.exec(text);
alert(matches.index); //5
alert(matches[0]); //bat
alert(pattern2.lastIndex); //8
test():
var text = “000-00-0000”;
var pattern = /\d{3}\-\d{2}-\d{4}/;
if (pattern.test(text)){
alert(“The pattern was matched.”);
}
Function Properties and Methods
length and prototype
arguments.callee.caller
alert(typeof falseObject); //object
alert(typeof falseValue); //boolean
alert(falseObject instanceof Boolean); //true
alert(falseValue instanceof Boolean); //false
The Number Type:
var num = 10;
alert(num.toFixed(2)); //”10.00”
var num = 10.005;
alert(num.toFixed(2)); //”10.01”
var num = 99;
alert(num.toPrecision(1)); //”1e+2”
alert(num.toPrecision(2)); //”99”
alert(num.toPrecision(3)); //”99.0”
var stringValue = “hello world”;
alert(stringValue.length); //”11”
Character Methods
var stringValue = “hello world”;
alert(stringValue.charAt(1)); //”e”
var stringValue = “hello “;
var result = stringValue.concat(“world”);
alert(result); //”hello world”
alert(stringValue); //”hello”
var stringValue = “hello world”;
alert(stringValue.slice(3)); //”lo world”
alert(stringValue.substring(3)); //”lo world”
alert(stringValue.substr(3)); //”lo world”
alert(stringValue.slice(3, 7)); //”lo w”
alert(stringValue.substring(3,7)); //”lo w”
alert(stringValue.substr(3, 7)); //”lo worl”
var stringValue = “hello world”;
alert(stringValue.indexOf(“o”)); //4
alert(stringValue.lastIndexOf(“o”)); //7
var stringValue = “Lorem ipsum dolor sit amet, consectetur adipisicing elit”;
var positions = new Array();
var pos = stringValue.indexOf(“e”);
while(pos > -1){
positions.push(pos);
pos = stringValue.indexOf(“e”, pos + 1);
}
alert(positions); //”3,24,32,35,52”
var text = “cat, bat, sat, fat”;
var pattern = /.at/;
//same as pattern.exec(text)
var matches = text.match(pattern);
alert(matches.index); //0
alert(matches[0]); //”cat”
alert(pattern.lastIndex); //0
var text = “cat, bat, sat, fat”;
var pos = text.search(/at/);
alert(pos); //1
var text = “cat, bat, sat, fat”;
var result = text.replace(“at”, “ond”);
alert(result); //”cond, bat, sat, fat”
result = text.replace(/at/g, “ond”);
alert(result); //”cond, bond, sond, fond”
function htmlEscape(text){
return text.replace(/[ < > ” & ]/g, function(match, pos, originalText){
switch(match){
case “ < ”:
return “ & lt;”;
case “ > ”:
return “ & gt;”;
case “ & ”:
return “ & amp;”;
case “\””:
return “ & quot;”;
}
});
}
var colorText = “red,blue,green,yellow”;
var colors1 = colorText.split(“,”); //[“red”, “blue”, “green”, “yellow”]
var colors2 = colorText.split(“,”, 2); //[“red”, “blue”]
var colors3 = colorText.split(/[^\,]+/); //[“”, “,”, “,”, “,”, “”]
The Prototype Pattern:
Prototypes and the in Operator
function Person(){
}
Person.prototype.name = “Nicholas”;
Person.prototype.age = 29;
Person.prototype.job = “Software Engineer”;
Person.prototype.sayName = function(){
alert(this.name);
};
BOM:
window
top
parent(fram)
self
Window Position:
var leftPos = (typeof window.screenLeft == “number”) ?
window.screenLeft : window.screenX;(screenX firefox)
var topPos = (typeof window.screenTop == “number”) ?
window.screenTop : window.screenY;
//move the window to the upper-left coordinate
window.moveTo(0,0);
//move the window down by 100 pixels
window.moveBy(0, 100);
//move the window to position (200, 300)
window.moveTo(200, 300);
//move the window left by 50 pixels
window.moveBy(-50, 0);
Window Size:
var pageWidth = window.innerWidth,
pageHeight = window.innerHeight;
if (typeof pageWidth != “number”){
if (document.compatMode == “CSS1Compat”){
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
Intervals and Timeouts:
setTimeout(function() {
alert(“Hello world!”);
}, 1000);
clearTimeout(timeoutId);
这个可以重复执行的哦
setInterval(function() {
alert(“Hello world!”);
}, 10000);
clearInterval(intervalId);
use the timeout to replace intervals, example:
var num = 0;
var max = 10;
function incrementNumber() {
num++;
//if the max has not been reached, set another timeout
if (num < max) {
setTimeout(incrementNumber, 500);
} else {
alert(“Done”);
}
}
setTimeout(incrementNumber, 500);
The location Object:
浙公网安备 33010602011771号