JavaScript Learning Notes

Source: Internet
Author: User
Tags arithmetic operators

JavaScript and HTML combined
Directly embedded in the HTM
<script type= "Text/javascript" >alert ("Hello world!"); </script>
Encapsulated into the JS file, then introduced
Hello.js
Alert ("hello!");
<script type= "Text/javascript" src= "Hello.js"/>

JS variable (belongs to the weak type)
JS in the definition of variables with the keyword VAR, non-rigorous, without var can also be directly defined variables

Arithmetic operators
Alert ("a=" + a/1000*1000);//a=3710
Alert ("//a=121" + 1);
Alert ("1");//a=11
Alert (true);//true
Alert (true + 1);//2
Alert (false + 1);//0
alert (false-1);//-1
alert (2%5==0);//false

Other operators
var t=4;
alert (!t);//false
Alert (3>0?alert ("Yes"): Alert ("No"));//yes->undefined
var xx;
Alert (xx);//undefined
alert (xx==undefined);//true
Alert (typeof ("abc"));//string
Alert (typeof (9));//number
Alert (typeof (True));//boolean
Alert (typeof (ABC) = = ' string ');//true

Statement
var x= "abc";
Switch (x) {
     case "PK":
         Alert ("PK") ;
         break;
     Case "abc":
         Alert ("abc");
         break;
     Default:
         alert ("OK");
         break;

}
document.write ("abc");//output directly to the page
99 Multiplication Table:
<script type= "Text/javascript" >
document.write ("<table>");
for (Var x=1;x<=9;x++) {
document.write ("<tr>");
for (Var y=1;y<=x;y++) {
document.write ("<td>");
document.write (y + "*" + x + "=" + y*x);
document.write ("</td>");
}
document.write ("</tr>");
}
document.write ("</table>");
</script>

Array
There are two ways to define arrays in JavaScript
var arr=[];var arr=[3,5,6];
Use the Array object to complete the
var arr = new Array ();//var arr=[];
var arr1 = new Array (5);//defines an array length of 5
var arr2 = new Array (5,6,7);//define an array with an element of 5,6,7
Characteristics
The length is variable and the type is arbitrary.

Function
function Show (x, y) {
Alert (x+ ":" +y);
}
Show ();//undefined:undefined
Show (//1:2);
Show (1);//1:undefined
Show (1,2,3,4);//The function has an array to store the arguments passed in, and this array is arguments, so arguments.length=4

function Getsum () {
return 100;}
The Var sum=getsum;//getsum itself is a function name, and the function itself is an object in JS. Getsum is the reference to this function object and assigns the address getsum this reference to sum. The sum also points to the function object.
alert (sum);//print if sum points to a function object, the string representation of the function object is printed, which is the code definition format of the function.

Dynamic functions
Using a function object built into JS
var add = new Function ("X, Y", "var sum; Sum=x+y;return sum;");
var he = Add (4,8);
alert (he);//12

anonymous functions
var xixi=function () {
Alert ("Hello");
}
Equivalent to
function haha () {
Alert ("Hello");
}
var Xixi=haha;
Xixi ();
Ten, practice
<script type= "Text/javascript" >

var arr = [66,13,37,21,89,17];
The maximum value is taken.
function Getmax (arr) {
var max = 0;
for (var x=1; x<arr.length; x + +) {
if (Arr[x]>arr[max])
max = x;
}
return Arr[max];

}

var maxValue = Getmax (arr);
Alert ("MaxValue:" +maxvalue);
Sort.

function Sortarray (arr) {
for (var x=0; x<arr.length-1; x + +) {
for (var y=x+1; y<arr.length; y++) {
if (Arr[x]>arr[y]) {
Swap (arr,x,y);
}
}
}
}
The position displacement of an element in an array.
Function Swap (arr,x,y) {
var temp = arr[x];
ARR[X] = Arr[y];
Arr[y] = temp;
}
function println (val) {
document.write (val+ "<br/>");
}
document.write ("Before sorting:" +arr);
println ("Before sorting:" +arr)
Sortarray (arr);
println ("After sorting:" +arr)
document.write ("After sorting:" +arr);
</script>
<script type= "Text/javascript" >

Find.
function Searchelement (arr,key) {

for (var x=0;x<arr.length; x + +) {
if (Arr[x]==key)
return x;
}
return-1;
}

Binary, there must be a premise. Must be an ordered array.
function BinarySearch (arr,key) {

var Max,min,mid;
min = 0;
max = arr.length-1;

while (Min<=max) {
Mid = (max+min) >>1;

if (Key>arr[mid])
Min = mid + 1;
else if (Key<arr[mid])
max = mid-1;
Else
return mid;
}
return-1;

}

The reversal of an array.
function Reversearray (arr) {
for (var start=0,end=arr.length-1; start<end; start++,end--) {
Swap (arr,start,end);
}
}
Reversearray (arr);
println ("After reversal:" +arr);
</script>
</body>

Global variables and local variables,
The variables defined in the script fragment are global variables. The variable defined in the function is a local variable.
<script type= "Text/javascript" >
var x = 3;//global variable x.
Function Show () {//variable x for local functions
x = 8;
}
Show ();
document.write ("x=" +x);//x=3;
</script>
Common objects
String
var str = "ABCDE";
println ("len=" +str.length);
println (Str.bold ());//Bold
println (Str.fontcolor ("Red"));//Font color.
println (Str.link ("http://www.163.com"));//Converts a string into a hyperlink.
println (Str.substr (1,3));//BCD
println (str.substring (1,3));//BC
String Custom method
Removes spaces at both ends of the string.
function Trim (str) {
var start,end;
start=0;
End=str.length-1;
while (Start<=end && str.charat (start) = = ") {
start++;
}
while (Start<=end && str.charat (end) = = "") {
end--;
}
Return str.substring (start,end+1);
}
Prototype

(1) Add a property to the prototype of string.
String.prototype.myLen = 199;
Alert ("ABC". mylen);//199

  
  
  
  
Adds a method to the prototype of string.

* New function of string object to remove whitespace at both ends of string.
String.prototype.trim = function () {
var start,end;
start=0;
End=this.length-1;
while (Start<=end && this.charat (start) = = ") {
start++;
}
while (Start<=end && this.charat (end) = = "") {
end--;
}
Return this.substring (start,end+1);
}
Alert ("-" + "AB CD". Trim () + "-");//-ab cd-
  
* New String function, add a string to the character array, return an array
String.prototype.toCharArray = function () {
Defines an array.
var chs = [];
Stores every bit of character in a string into a character array.
for (var x=0; x<this.length; x + +) {
CHS[X] = This.charat (x);
}
return CHS;
}
  
* Add a method that reverses the string.
String.prototype.reverse = function () {
var arr = This.tochararray ();
Encapsulates the array position substitution feature. and defines the inside of the inversion function.
for (Var x=0,y=arr.length-1; X<y; x++,y--) {
Swap (arr,x,y);
}
Return Arr.join ("");//Convert a character array to a string
}
Function Swap (arr,a,b) {
var temp = Arr[a];
Arr[a] = arr[b];
ARR[B] = temp;
}
  
  
Common methods for array object arrays
function println (param) {
document.write (param+ "<br/>");
}
var arr = ["NBA", "haha", "CBA", "AAA", "ABC"];
var arr2 = ["QQ", "Xiaoqiang", 70];
println (arr);
println (ARR2);
var newArr = Arr.concat ("MM", arr2);//use mm as the element in the new array, and the elements in the ARR2 array as elements in the new array.
println (NEWARR);//nba,haha,cba,aaa,abc,mm,qq,xiaoqiang,70
println (Arr.join ("-"));//nba-haha-cba-aaa-abc//join () Default is join (",")
println (Arr.pop ());//abc//deletes and returns the last element.
println (Arr.shift ());//nba//deletes and returns the first element.
println (Arr2.reverse ());//70,xiaoqiang,qq//Reverse
println (Arr2.sort ());//70,qq,xiaoqiang//sort

var arr3 = ["NBA", "haha", "CBA", "AAA", "ABC"];
var temp = Arr3.splice (1,3,8080,9527, "Xixixi", "Wangcai"),//delete element and can be substituted for element.
println (temp);//haha,cba,aaa
println (ARR3);//nba,8080,9527,xixixi,wangcai,abc
println (Arr3.unshift ("uuuu"));//7//Insert Header returns the length of the new array
println (ARR3);//uuuu,nba,8080,9527,xixixi,wangcai,abc
  
Methods for customizing array objects using prototypes

Array.prototype.getMax = function () {
var temp = 0;
for (var x=1; x<this.length; x + +) {
if (This[x]>this[temp]) {
temp = x;
}
}
return this[temp];
}
* The string representation of the array.
* Define the ToString method. Equivalent to a replication in Java.
Array.prototype.toString = function () {
Return "[" +this.join (",") + "]";
}

var array = ["NBA", "haha", "CBA", "AAA", "ABC"];
var maxValue = Array.getmax ();
println ("MaxValue:" +maxvalue);//maxvalue:nba
println (Array.tostring ());//[nba, haha, CBA, AAA, ABC]

Common Methods for Date objects
1, get current time 2012-10-17 16:19:32 Wed
function GetCurrentTime () {
var d=new Date ();
var month = Add_zero (D.getmonth () +1);
var days = Add_zero (D.getdate ());
var hours = Add_zero (D.gethours ());
var minutes = Add_zero (D.getminutes ());
var seconds = Add_zero (D.getseconds ());
var week = Getweek (D.getday ());
var currenttime=d.getfullyear () + "-" +month+ "-" +days+ ""
+hours+ ":" +minutes + ":" +seconds + "" +week;
return currenttime;
}

function Getweek (num) {
var weeks = [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '];
return Weeks[num];
}

function Add_zero (temp)
{
if (temp<10) {return "0" +TEMP;}
else{return temp;}
}

document.write (GetCurrentTime ());

2, the conversion between the date object and the millisecond value.
var date2 = new Date ();//Gets the millisecond value. The Date object--the millisecond value.
var time = Date2.gettime ();
println (time);//1350462546374
Turns the millisecond value into a Date object. Method: New Date (time);
var date3 = new Date (1230462546374);
document.write (date3)//sun Dec 19:09:06 utc+0800 2008

3. Convert the Date object to and from the string.
The date object is turned into a string. toLocaleString Date and time tolocaledatestring date
Turns a string into a Date object. A date string with the specified format--millisecond value---> Date object.
var str_date = "9/28/2017";
var time2 = Date.parse (str_date);
var date3 = new Date (time2);
println (Date3.tolocaledatestring ());//September 28, 2017

4. With () usage
* To simplify the writing of object invocation content.
* You can use the unique statements in JS to complete.
Format
* With (object)
* {
* The contents of the specified object can be used directly in the region. No need to write "object."
* }
With (date) {
var year = getFullYear ();
var month = GetMonth () +1;
var day = GetDate ();
var week = Getweek (GetDay ());
}

Math Object
* Demo Math object. The methods in the object are static. You do not need new, just call math.
*/
var num1 = Math.ceil (-12.34);//returns the smallest integer greater than or equal to the specified parameter. -12 axes upward
var num2 = Math.floor (-12.34);//returns the largest integer less than or equal to the specified data//-13 axis down
var num3 = Math.Round (-12.54);//Rounding//-13

var num4 = Math.pow (10,2);//100

JavaScript Learning notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.