您的位置:首页 > Web前端 > JavaScript

js基础2

2016-03-28 18:14 525 查看
toFixed() returns a string, with the number written with a specified number of decimals:
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560

Number(), can be used to convert JavaScript variables to numbers:
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN

parseInt() parses a string and returns a whole number
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

parseFloat() parses a string and returns a number.

valueOf() returns a number as a number.to convert Number objects to primitive values.
There is no reason to use it in your code.
-----------------------------------------------------------------------------------------------------------------

Math.random(); // returns a random number

------------------------------------------------------------------------------------------------------------------

判断是不是数组:
To solve this problem ECMAScript 5 defines a new method Array.isArray():

1.Array.isArray(fruits); // returns true
2.function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
3.fruits instanceof Array // returns true
--------------------------------------------------------------------------------------------------------------------
关于数组的sort()

By default, the sort() function sorts values as strings.
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a>b});

----------------------------------------------------------------------------------------------------------
the Boolean() function to find out if an expression (or a variable) is true:

------------------------------------------------------------------------------------------------------------
The constructor property returns the constructor function for all JavaScript variables.
"John".constructor // Returns function String() { [native code] }
(3.14).constructor // Returns function Number() { [native code] }
false.constructor // Returns function Boolean() { [native code] }
[1,2,3,4].constructor // Returns function Array() { [native code] }
{name:'John', age:34}.constructor // Returns function Object() { [native code] }
new Date().constructor // Returns function Date() { [native code] }
function () {}.constructor // Returns function Function(){ [native code] }
-----------------------------------------------------------------------------------------------------
The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.

Regular Expression Modifiers
/pattern/modifiers;

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n

---------------------------------------------------------------------------------------------------------------

RegExp Object

var patt = /e/;
patt.test("The best things in life are free!"); //true
上述等价于:
/e/.test("The best things in life are free!");

exec()
It searches a string for a specified pattern, and returns the found text.If no match is found, it returns null.

---------------------------------------------------------------------------------------------------------------

JavaScript异常处理
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.

<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}

try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
</script>
---------------------------------------------------------------------------------------------------------------------

The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.

This has the same function as setting a breakpoint in the debugger.

If no debugging is available, the debugger statement has no effect.

With the debugger turned on, this code will stop executing before it executes the third line.

-----------------------------------------------------------------------------------------------------------------
Strict mode is declared by adding "use strict"; to the beginning of a JavaScript or a JavaScript function.

Declared at the beginning of a JavaScript file, it has global scope (all code will execute in strict mode):

"use strict";
x = 3.14; // This will cause an error (x is not defined)

-----------------------------------------------------------------------------------------------------------------
Loops are often used in programming.

Each statement in a loop, including the for statement, is executed for each iteration of the loop.

Search for statements or assignments that can be placed outside the loop.

Bad Code:
for (i = 0; i < arr.length; i++) {
Better Code:
l = arr.length;
for (i = 0; i < l; i++) {

---------------------------------------------------------------------------------------------------------
An alternative is to use defer="true" in the script tag. The defer attribute specifies that the script should be executed after the page has finished parsing, but it only works for external scripts.

或者:
<script>
window.onload = downScripts;

function downScripts() {
var element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
}
</script>
------------------------------------------------------------------------------------------------------------------
JavaScript JSON

JSON is a format for storing and transporting data.

JSON is often used when data is sent from a server to a web page.

JavaScript program can easily convert JSON data into native JavaScript objects.

JSON stands for JavaScript Object Notation
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
JSON names require double quotes.

{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

First, create a JavaScript string containing JSON syntax:

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:

var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:

-----------------------------------------------------------------------------------------------------
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}

--------------------------------------------------------------------------------------------------------
创建对象:

1. var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

2.var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

3.function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
--------------------------------------------------------------------------------------------------------

JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.

If y is an object, the following statement will not create a copy of y:

var x = y; // This will not create a copy of y.
The object x is not a copy of y. It is y. Both x and y points to the same object.

Any changes to y will also change x, because x and y are the same object.

-----------------------------------------------------------------------------------------------------------

The syntax for accessing the property of an object is:

objectName.property // person.age
or

objectName["property"] // person["age"]
or

objectName[expression] // x = "age"; person[x]
Note The expression must evaluate to a property name.

var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
//x相当于person的属性名
//John Doe 25

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];
//删除属性

All properties have a name. In addition they also have a value.

The value is one of the property's attributes.

Other attributes are: enumerable, configurable, and writable.

These attributes define how the property can be accessed (is it readable?, is it writable?)
---------------------------------------------------------------------------------------------------------

A JavaScript method is a property containing a function definition.

function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}

------------------------------------------------------------------------------------------------------
Every JavaScript object has a prototype. The prototype is also an object.

All JavaScript objects inherit their properties and methods from their prototype.

Objects created with new Date() inherit the Date.prototype.

The standard way to create an object prototype is to use an object constructor function:

Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

-------------------------------------------------------------------------------------------------
**************************************
Adding a Property to an Object
myFather.nationality = "English";

Adding a new method to an existing object is also easy:
myFather.name = function () {
return this.firstName + " " + this.lastName;
};

**************************************
To add a new property to a constructor, you must add it to the constructor function:

Prototype properties can have prototype values (default values).

或者这样也可以:
person.prototype.nationality = "English";

person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};

**************************************
After a function expression has been stored in a variable, the variable can be used as a function:
var x = function (a, b) {return a * b};
var z = x(4, 3);
Functions stored in variables do not need function names.

Functions can also be defined with a built-in JavaScript function constructor called Function().
然而这个没啥大用
**************************************

A self-invoking expression is invoked (started) automatically, without being called.Function expressions will execute automatically if the expression is followed by ().

(function () {
var x = "Hello!!"; // I will invoke myself
})();
**************************************
Arguments are Passed by Value
Objects are Passed by Reference
**************************************
**************************************
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: