Home>

I. Introduction

1.What is javascript

JavaScript is a client browser-based, object-oriented, event-driven web scripting language developed by Netscape.

Why use javascript

form validation

Web effects

Games

ajax

3.Quick start

In the program,If i want to write js code, there are two ways:

1) In the html file, in a pair of script tags, write directly

<script language="javascript">
  document.write ("hello");
</script>

2) In js, write directly,In html, use a pair of script tags to directly reference

<script language="javascript" src="demo01.js"></script>

The above two cannot be reused in a pair of script tags,References cannot write file contents.

Second, the basic grammar1.Basic format

javascript case sensitive Variable a and variable a are two variables JavaScript scripts must be embedded in html files Javascript cannot contain html tag code
<script>
  document.write ("<table></table>");
</script>

Write a script statement per line

You can add a semicolon at the end of the statement

JavaScript script can be saved as an external file independently

2.About script tagslanguage:referenced language javascript, php, c#, vbscript

src:reference an external js file

3.About variablesVariables are containers used to temporarily store values.Variable stored values ​​can change

Variables must be declared before they can be used.Declaring variables with var

Using var declarations:local variables

No var declaration:global variables

Variable naming rules:the first character must be an English letter,Or an underscore (_);the following characters,Can be English letters,Numbers, underscores;variable names cannot be reserved for JavaScript

Scope of variables:global variables, local variables

4, data type (if type language,Definition does not need to specify data types)string:String "" ""

number:the numbers 10, 10.01, 100

boolean:boolean true, false

undefined:undefined

null:empty

object:object type

<script language="javascript">
  //Use js to describe a person's complete information
  var name="Zhang San";
  var age=30;
  var marry=true;
  var height=1.8;
  document.write ("<ol>");
  document.write ("<li>name" + name + "</li>");
  document.write ("<li>age" + age + "</li>");
  document.write ("<li>Marriage" + marry + "</li>");
  document.write ("<li>height" + height + "</li>");
  document.write ("</ol>");
  function person () {}
  var p1=new person ();
  p1.name="Li Si";
  p1.age=20;2013/12/31
  document.write (p1.name + "<br>");
  document.write (p1.age + "<br>");
</script>

5.Operators1) Arithmetic operators

+,-, *, /,%, ++,-

i ++

++ i

<script>
var i=10;
var j=i ++;//Assign first and then add
var k=++ i;//first add and then assign
document.write (j);//10
document.write (k);//12
</script>

2) comparison operators

,< ;,>=,<=,! =, ==, ===,! ==

What is the difference between == and ===?

==:determine whether the values ​​are equal

===:The same type of judgment value

<script>
var i=5;//number
var j="5";//string
if (i == j) {
  document.write ("equal");
}
if (i === j) {
  document.write ("All equals");
}
</script>

3) logical operators

&& 、 || ,!

4) Assignment operator

=, + =,-=, * =,/=,%=

Evaluate the left and right of the operator,Assignment to the left

String operator

+, +=(Points are used in PHP)

Third, the process structure

Sequential structure

Branch structure

Cyclic structure

1.Sequence structure

Code is executed line by line

2.Branch structure

if, else, else if, switch

3.Circular structure

for, while, do .... while, for ..... in

Games:

Counting game:after entering the page, randomly counting 1–500, popping up the input boxA number entered by the user,If this number is greater than a random number,

<script language="javascript">
  var n=math.round (math.random () * 500);//random number
  alert (n);
  while (true) {
    var number=prompt ("Please enter a number between 0 and 500");//User input
    if (number>n) alert ("big");
    if (number<n) alert ("smaller");
    if (number == n) {
      alert ("The answer is correct ~~~~");
      break;
    }
  }
</script>

Fourth, functions

Function of the functionRepetitive code use

Modular programming

2. Grammar:

Must be defined before using the function

Function definition has three parts:function name, parameter list,Function body

Define the format of the function

** function function name ([parameter 1, parameter 2 ...]) {

Function execution part;

return expression;

} **

Calling syntax:

Function name (argument 1, argument 2, ...,);

3.Code example

Example 1:Definition and call of function

//Definition of function
  function display () {
    alert ("hello");
  }
  //function call
  display ();
  display ();
  display ();

Example 2:Question about function parameters

In the previous question,first, second are formal parameters, i, j are actual parameters

During function execution,Changes in parameter values ​​do not affect actual parameters

Pass by value

Pass the schematic diagram by address:

In js, the object type is passed by address by default

function display (obj) {
  obj.name="lisi";
}
var p1=new object ();
p1.name="zhangsan";
display (p1);
alert (p1.name);//lisi
alert (p1);

The basic types of js,Are passed by value.

var a=1;
function foo (x) {
  x=2;
}
foo (a);
console.log (a);//still 1, unaffected by x=2 assignment

Look at the object again:

var obj={x:1};
function foo (o) {
  o.x=3;
}
foo (obj);
console.log (obj.x);//3, modified!

Shows that o and obj are the same object,o is not a copy of obj. So instead of passing by value. But does this mean that js objects are passed by reference?Let's look at the following example:

var obj={x:1};
function foo (o) {
  o=100;
}
foo (obj);
console.log (obj.x);//still 1, obj has not been modified to 100.

If passed by reference,Modifying the value of the parameter o should affect the actual parameter.But changing the value of o here does not affect obj. So objects in js are not passed by reference.So how exactly is the value of the object passed in js?For object types,Because the object is mutable, modifying the object itself will affect the reference and copy of the reference sharing the object.And for basic types,Since they are both immutable, there is no difference between pass-by-share and call by value.So the basic types of js are both passed by value,Also eligible for pass-by-share.

var a=1;//1 is a number type, immutable var b=a;b=6;

According to the evaluation strategy passed by sharing,a and b are two different references (b is a duplicate copy of a), but references the same value.Since the basic type number 1 is immutable, there is no difference between passing by value and passing by share.

Immutable properties of primitive types

The basic types are immutable, only objects are mutable. For example, the numeric value 100, the boolean true, false, and modifying these values ​​(such as changing 1 to 3 and changing true to 100) does not What meaning.More misunderstood,Is a string in js. Sometimes we try to "change" the contents of the string,But in JS, any "modify" operation that seems to modify the string value is actually creating a new string value.

var str="abc";
str [0];//"a"
str [0]="d";
str;//still "abc";assignment is invalid.
No way to modify the contents of the string

The object is different,Objects are mutable.

var obj={x:1};
obj.x=100;
var o=obj;
o.x=1;
obj.x;//1, modified
o=true;
obj.x;//1, will not change due to o=true

Here you define the variable obj, the value is object, and then set the value of the obj.x property to 100. Then define another variable o, the value of which is still the object object. At this time, the values ​​of the two variables obj and o point to the same object (a reference that shares the same object). So modify the content of the object,Has an effect on both obj and o.But objects are not passed by reference,Modifying the value of o with o=true does not affect obj.

Example 3:About the return value of a function

function display (first, second) {
    //The function returns immediately upon return.
The following code is not executed
    return first + second;
  }
  var i=10;
  var j=20;
  alert (display (i, j));
  document.write (display (i, j));* /

Example 4:About anonymous functions

 /* var i=function () {
    alert ("hello");
  };
  i ();* /
var i=10;variables can hold data,Can also save addresses
function display () {
} Add a variable called display under the window object, which points to the first address of this function
window.i=display We let i under the window object point to the first address of this function
display () ======== i ();

Example 5:Self-calling anonymous function

<script language="javascript">
  /* var i=function () {
    alert ("hello");
  };
  i ();* /
  (function (first) {
  alert (first);
  alert ("hello, js");
  }) (10)
</script>
function () {}:equivalent to returning the first address
(function () {}):treat this part as a whole
(function () {}) ():equivalent to finding this address and executing

The above way of writing:you can avoid the function of the code in the code library,And the above code will only be executed once at runtime,Generally used for initialization.

Example 6:Global and local variables

<script>
  function display () {
    //var i=20;//local variables only work in local scope
    i=20;//Global, will modify the value of global i to 20
  }
  display ();
  alert (i);
</script>

What is defined inside a function is local,Otherwise it is global

If a variable in a function does not have a var declaration, it will directly affect the global

Why is no var global?

It is because in js, if a variable does not have a var declaration, it will automatically go to the previous scope to find the declaration statement of this variableIf found,Use it, if not found,Keep looking up,Until the global scope,If there is still no declaration for this variable in the global,Then it will be declared in the global scope automatically,This is the scope chain in js

Code example:

<script>
  var i=10;
  function fn1 () {
    var i=100;
    function fn2 () {
      i=1000;
      function fn3 () {
        i=10000;
      }
      fn3 ();
      console.log (i);//10000
    }
    fn2 ();
    console.log (i);//10000
  }
  fn1 ();
  console.log (i);//10
</script>

Local access globally using scope chain

Global access to local can be simulated using (function) closures.

Five, the use of drugs

Inside a function,You can use the arguments property, which represents the parameter list of a function,It is represented as an array

Example 1:When defining a display function, its number of actual parameters must be consistent with the number of formal parameters.Sometimes when we define a function,The parameter parameters cannot be fixed.How to solve?

<script>
function display () {
  //No formal parameters defined,Then all formal parameters are automatically stored in the attributes array of arguments
  for (var i=0;i<arguments.length;i ++) {
    document.write (arguments [i] + "<br>");
  }
}
display ("lisi", "zhangsan", "wangwu");//Three arguments
display ("zhangsan", "lisi", "wangwu", "xiaoqiang", "wangcai");//Five arguments
</script>

If defined,The number of parameters is uncertain,All arguments can be saved by arguments

Example 2:Use js function to calculate the total salary of employees in each company

<script>
  function display () {
    var sum=0;//Total
    for (var i=0;i<arguments.length;i ++) {
      sum +=arguments [i];
    }
    document.write (sum + "<br>");
  }
  //a company
  display (10000,2000,5000);
  //b company
  display (1000, 2000, 5000, 8000, 10000);
</script>
  • Previous Example to explain the creation of basic animation for iOS application UI development
  • Next Simple implementation to limit the number of uploadify uploads