94_111122114208_1

JS Beginner Basics

Steps to Write JS

  1. First Implement the Layout
  2. Figure Out the Implementation Principle
  3. Understand JS Syntax

Implementation for Removing a Specific Element

  • display: none; displayed as nothing
  • visibility: hidden; hide
  • width \ height
  • Transparency
  • left \ top
  • Use a div with the same background color to cover the element
  • Use margin values
  • ……

Get Element

  • getElementById() — static method, can only be preceded by document
  • document.body, document.title — elements that appear only once on the page
  • getElementsByTagName() — dynamic method, can be preceded by document or other elements, returns an array-like collection of elements
    • Has an array-like length
    • Has array-like usage, such as ali
    • When using TagName, you must add square brackets []
    • The so-called dynamic method means that elements dynamically added via JS can also be found by getElementsByTagName(), but document.getElementById cannot find them.

Events

Events: mouse events, keyboard events, system events, form events, custom events
  • onclick
  • onmouseover
  • onmousedown
  • onmouseout
  • onmouseup
  • onmousemove
  • ……

How to Add Events

  • element.onmouseover

Functions

Functions can be understood as commands to do something, e.g.: function abc() { // It will definitely not execute by itself! ... }
  1. Direct call: abc();
  2. Event call: element.event = function name (oDiv.onclick = abc;)
  3. ……
function(){} anonymous function element.event = function(){}

Testing

  • alert(1); alert box with OK button; alert('ok'); 'ok' is a string
  • Beginners: It's best to keep the habit of writing and testing at any time

Variables

  • var li = document.getElementById('lis');
  • var num = 123;
  • var name = 'leo';

JS Attribute Operations

HTML Attribute Operations

  • Attribute name
  • Attribute value
  • Reading an attribute: get, find
    • element.attributeName
  • Writing an attribute: replace, modify
    • element.attributeName = new value
    • To add, you need to use +=
  • innerHTML reads all HTML code inside an element.
String concatenation: plus sign.

Notes on Reading and Writing Attributes

  • Hyphens are not allowed in JS properties; for example, font-size is changed to fontSize.
  • "class" is a reserved word in JS; to use class in JS, use className.
  • Don't use relative paths for judgments (e.g., img's src, and also href).
  • Don't use color values for judgments (because there are forms like red, #f00, rgb(250, 0, 0), etc.).
  • Don't use relative paths for judgments either.
  • Don't use innerHTML's value for judgments.
  • In IE6, IE7, IE8, the type of form elements cannot be changed; it's not supported and will throw an error; everything else can.
  • In some browsers, directly changing the float value may not be supported. In JS, you can treat IE (styleFloat) and non-IE (cssFloat) differently.
  • For things that cannot be used for judgment, you can create a switch and use a boolean value to implement it.
About compatibility:
  • Technically: you must be able to master compatibility (solutions to compatibility issues).
  • On requirements: discuss and work it out (provide the most accurate rendering solution).

Using Square Brackets []

  • The value after the dot "." cannot be modified.
  • The value inside square brackets [] can be modified; in JS, "." can be replaced with "[]".

Conditional Judgment

  • if (condition) { ... };
  • if (condition) { ... } else { ... };
  • if (condition1) { ... } else if (condition2) { ... } else if (condition3) { ... } else { ... };

Arrays

  • "Warehouse for storing data."
  • Square brackets [], separated by half-width commas, do not add a comma after the last data item.
  • The length property of an array.
  • Use push() to append things to the end of an array.

for Loop Application

Use cases for for loops:
  • If you want to repeatedly execute certain code.
  • Each time it executes, a number changes.
Execution order of a for loop: 1 → 234 → 234 ...
  1. var i = 0;
  2. i < 3; critical step.
  3. All code inside the parentheses.
  4. i++
Note the following loop:
for (var i=0; i<aLi.length; i++) {
  aLi[i].onclick = function(){
    alert(i);
  }
}
The above code will alert a 3, instead of 0, 1, 2 in sequence. Note here: if a function is wrapped inside the for loop and the function uses i, then due to scope, i will not increment one by one as you might expect.

cssText Text Formatting and Attribute Operations

  • oDiv.style.cssText = 'width: 200px; height: 200px;';
  • cssText does not touch the settings in the style tag in the head; but it will change inline styles (note: it replaces inline styles, not adds new inline styles).

Idea for Not Repeating the Function After Button Click

  1. Mess with the button, e.g., after one click, set oBtn.disabled = true;
  2. Continue messing with the button, e.g., after one click, hide the button: oBtn.style.display = 'none';
  3. Clear what the button added, then add it again; clear first, then generate.
  4. Use a judgment (conditional).

this Pointing and this Application

window is the "boss" in JS.
function fn1(){
    alert(this);
}
fn1();
In the code above, executing function fn1() is equivalent to window.fn1(); therefore, alerting this inside the function body is still window.
function fn1(){
    alert(this);
}
oBtn.onclick = fn1;
In the above, the fn1 function called by the button's click event finally alerts the button itself, not window.
function fn1(){
    alert(this);
}
oBtn.onclick = function(){
    alert(this)
}
In the above code, clicking the button, the alerted this is still the button oBtn.
function fn1(){
    alert(this);
}
oBtn.onclick = function(){
    fn1();
}
In the above code, clicking the oBtn button, what is alerted is no longer the oBtn object, but window.
<input id="btn2" type="button" value="按钮2" onclick="alert(this)" />
The above code is an inline event, and the alerted this is the button btn2.
function fn1(){
    alert(this);
}
<input id="btn2" type="button" onclick="fn1();" value="按钮2” />
In the above code, the alerted this is window.
  • this: the object that calls the current method (function).
function fn1(){
    this
}

fn1(); this => window

oDiv.onclick = fn1; this => oDiv

oDiv.onclick = function(){
    this => oDiv
};

oDiv.onclick = function(){
    fn1(); fn1()里面的this => window
}

<div onclick="  this  "></div> this => div

<div onclick = "  fn1();  "></div>  fn1()里面的this => window
<script>

fn1(this);
function fn1(obj){
  obj => window
}

oDiv.onclick = function(){
  this
  fn1(this);
};
function fn1(obj){ obj => oDiv }

</script>
<input type="button" value="按钮1" />
<input type="button" value="按钮2" />
<input type="button" value="按钮3" />

window.onload = function(){
  var aBtn = document.getElementsByTagName('input');
  for(var i=0; i<aBtn.length; i++) {
    aBtn[i].onclick = function(){
      this.style.background = 'yellow';
    }
  }
}
The effect of the above code is equivalent to the following code; note the usage of that.
<input type="button" value="按钮1" />
<input type="button" value="按钮2" />
<input type="button" value="按钮3" />

window.onload = function(){
  var aBtn = document.getElementsByTagName('input');
  var that = null; 
  
  for(var i=0; i<aBtn.length; i++) {
    aBtn[i].onclick = function(){
      that = this;
      fn1();
    };
  }
  function fn1(){
    //this => window
    that.style.background = 'yellow';
  }
}
The above code is also equivalent to the following code:
<input type="button" value="按钮1" />
<input type="button" value="按钮2" />
<input type="button" value="按钮3" />

window.onload = function(){
  var aBtn = document.getElementsByTagName('input');
  
  for(var i=0; i<a.aBtn.length; i++) {
    aBtn[i].onclick = fn1; //注意不要在fn1后面加括号
  }
  
  function fn1(){
    this.style.background = 'yellow';
  }
}

Custom Attributes, Index Values

Reading and Writing Custom Attributes

window.onload = function(){
  var aBtn = document.getElementsByTagName('input');
  
  aBtn[0].abc = 123; //自定义属性
  
  // alert(aBtn[0].abc); 自定义属性的读
  // aBtn[0].abc = 456; 自定义属性的写
}
JS can add any number of custom attributes to any HTML element.

Custom Attribute Application

Using custom attributes, you can add a switch property to an element to serve as a control switch. For example, the following:
window.onload = function(){
  var aLi = document.getElementsByTagName('li');
  // var onOff = true; 一个onOff只能控制一个开关。要为多个元素设置各自的开关,就要给每个元素加个onOff开关。
  
  for(var i=0; i<aLi.length; i++) {
    aLi[i].onOff = true;
    aLi[i].onclick = function(){
      if (this.onOff){
        this.style.background = 'url(img/active.png)';
        this.onOff = false;
      } else {
        this.style.background = 'url(img/normal.png)';
        this.onOff = true;
      }
    }
  }
}

Get Its Own Incrementing Number and Match Array Content

Set three buttons on the page with a default value of 0; each time a button is clicked, the letters cycle through A, B, C, D sequentially.
<input type="button" value="0" />
<input type="button" value="0" />
<input type="button" value="0" />
  var aBtn = document.getElementsByTagName('input');
  var arr = ['A', 'B', 'C', 'D'];
  
  for(var i=0; i<aBtn.length; i++){
    aBtn[i].num = 0;
    aBtn[i].onclick = function(){
      this.value = arr[this.num]
      this.num++;
      if(this.num === arr.length){
        this.num = 0;
      };
    };
  };

Add Index Value, Match Array, HTML Element

Match the values of the three buttons with the values in the array in sequence.
<input type="button" value="btn1" />
<input type="button" value="btn2" />
<input type="button" value="btn3" />
window.onload = function(){
  var aBtn = document.getElementsByTagName('input');
  var arr = ['莫涛','张森','杜鹏'];
  
  for(var i=0; i<aBtn.length; i++){
    aBtn[i].index = i; //自定义属性index,添加索引值
    aBtn[i].onclick = function(){
      //alert(i); //不会弹出1、2,直接弹出3,也就是aBtn的长度。也就是说,在基础阶段,在for循环所包的函数里面再用i是不靠谱的。
      this.value = arr[this.index];
    };
  };
}
The above matches array values by index value; matching HTML elements is the same. If you want to establish a "matching" or "corresponding" relationship, use index values.

Data Types, Type Conversion

ECMAScript:Standard, core.

Data Types

  • HTML tag types.
    • block
    • inline
    • inline-block
    • table
    • ……
  • Data types in JS:
    • Number (NaN belongs to the number type).
    • String.
    • Boolean.
    • Function type.
    • Object.
      • obj
      • []
      • {}
      • null (null/empty cannot have custom properties added).
    • Undefined.
typeof is used to determine data types. String method charAt(): obtains a substring by the string's index. Objects can have custom properties added. If you assign a function to an object, you have added a method to that object.

JS Data Type Conversion

Methods to convert strings to numbers:

JS Method: Number();

var a = '100';
alert(a + 100); //'100100'

var b = '00100';
alert(Number(b)); //100

var c = '+100';
alert(Number(c)); //100

var d = '';
alert(Number(d)); //0

var e = '   ';
alert(Number(e)); //0

var f = true;
alert(Number(f)); //1

var g = false;
alert(Number(g)); //0

var i = [];
alert(Number(i)); //0 空数组用Number转出来是0

var j = [''];
alert(Number(j)); //0

var k = [123];
alert(Number(k)); //123

var l = ['123'];
alert(Number(l)); //123

var o = null;
alert(Number(o)); //0

----------------------------
var m = [1,2,3];
alert(Number(m)); //NaN

var json = {abc:123};
alert(Number(json)); //NaN

var json2 = {};
alert(Number(json2)); //NaN 即使是空json,Number方法也转不了

var h = function(){};
alert(Number(h)); //NaN

var p;
alert(Number(p)); //undefined 

var q = '100px';
alert(Number(q)); // NaN

parseInt and parseFloat

var a = '100px';
alert(parseInt(a)); //100

var b = '100px123456789';
alert(parseInt(b)); //100

var d = '-100px';
alert(parseInt(d)); //-100 parseInt还是认加减号的

var e = '   100px';
alert(parseInt(e)); //100 parseInt也是认空格的

var f = '000000100px';
alert(parseInt(f)); //100

var g = '12.34元';
alert(parseInt(g)); //12 parseInt只能转出整数
------------------------------
var c = true;
alert(parseInt(c)); //NaN

//parseInt也不能用于转函数等

The parseInt() method also has a parameter, which is the radix to convert by; for example, parseInt(a, 10) means convert in decimal; parseInt(b, 2) means convert in binary.
var a = '12.34元';
alert(parseFloat(a)); //12.34

var b = '12.3.4元';
alert(parseFloat(b)); //12.3 parseFloat只认第一个小数点
Combined use of parseInt and parseFloat., it can be used to determine whether a value is an integer or a decimal, as follows:
var num = '200.345';
if(parseInt(num) == parseFloat(num)) {
  alert(num + '是整数');
} else {
  alert(num + '是小数');
}

Weird Implicit Type Conversions in JS

Explicit type conversion (forced type conversion):
  • Number();
  • parseInt();
  • parseFloat();
Implicit type conversion:
  • - * / % subtraction, multiplication, division, modulo can convert strings to numbers.
  • The + plus sign can convert numbers to strings.
  • ++ -- increment and decrement operators can convert strings to numbers.
  • < > greater-than and less-than signs can convert strings to numbers; be sure to note whether the comparison is numeric or string comparison.
  • ! negation converts the data type on the right to a boolean value.
  • ==
alert('200' - 3); //197
alert(200 + '3'); //2003

var a = '10';
a++;
alert(a); //11

alert('10'>9); //true
alert('1000000'>'9'); //false
//注意:数字的比较和字符串的比较不同;字符串的比较是一位一位的比较。

alert(!'ok'); //false
alert(!100); //false

alert('2' == 2); //true
alert('2' === 2); //false 三个等号不仅判断值,还会先判断两者的类型
If implicit type conversion cannot convert, it also returns NaN; for example, alert('...' - 9); will alert NaN.

isNaN Application Example

NaN: (not a number). NaN is a number type that is not a number. All numbers are of the number type, but not all number types are numbers.
  • NaN is a number type, but it is not a number.
  • Once NaN appears in a program, it definitely indicates that an illegal operation was performed.
  • NaN is a false (falsy value).
  • NaN is not even equal to itself.
var a = Number('abc');
//alert(a); //NaN
//alert(typeof(a)); //number

if(a) { //会弹出‘假’,说明NaN是false
  alert('真');
} else {
  alert('假');
}

//alert(a === a); //false NaN比较,比出false
isNaN:"is not a Number" means asking "is it not a number?" (not a number). isNaN(); is a method used to do the work.
  • Helps determine whether a certain value is a number.
  • It dislikes numbers, hates numbers (not hating the number type; isNaN likes NaN very much, returning true, but NaN is a number type). It is used to judge numbers. For example, alert(isNaN(2)); returns false. alert(isNaN('I love you')); returns true. alert(isNaN(function(){})); returns true.
isNaN's judgment process: it passes what's inside the parentheses to Number. If Number converts it to a number, it returns false; if it cannot convert, it returns true.
alert(isNaN('250'));
//Number() '250' => 250 => false

alert(isNaN(true));
//Number() true => 1 => false

alert(isNaN([]));
//Number() [] => 0 => false
Below is a small application of isNaN:
<input type="text" />
<input type="button" value="判断输入值是不是数字" />
window.onload = function(){
  var aInp = document.getElementsByTagName('input');
  var str = '';
  
  aInp[1].onclick = function(){
    str = aInp[0].value
    //alert(type of str); //总是返回string 从HTML中拿到的内容,类型都是字符串
    
    if(isNaN(str)){
      alert(str + '不是数字');
    } else {
      alert(str + '是数字');
    }
  }
}

Function Parameter Passing

Parameters = JS data types:
  • Number.
  • String.
  • Boolean.
  • Function.
  • Object.
  • Undefined.

Parameter Type Checking

fn1(100);
fn1('miaov');
fn1(function(){alert(1);});

function fn1(a){
  if(typeof a === 'number' &amp;&amp; a === a) {
    alert(a+20);
  } else if (typeof a === 'string'){
    alert(a.charAt(2));
  } else if (typeof a === 'function'){
    a();
  }
}

Steps for Reusing Code

  1. Try to keep the HTML code structure consistent; you can select child elements through the parent.
  2. Implement the core main program and wrap it in a function.
  3. Find the different values in each group and implement them via parameter passing.

JS Scope

What is scope.
  • Domain: space, range, area.
  • Function: read, write.

The Browser's "JS Parser"

"JS parser": a program in the browser specifically used to read JS. It does at least the following two things (of course, there are other things):
  1. Preparation ("look for things"): look for things based on var, function, and parameters —JS pre-parsinga = undefined. All variables, before the code is actually run, are assigned a value in advance: undefined. fn1 = function fn1(){alert(2);} All functions, before the code is actually run, are the entire function block. If there are duplicate names, only one is kept.
  2. Interpret the code line by line. Every time a line is read, it goes back to the pre-parsed library to take a look. When encountering an expression (with = + - * / % ++ – ! parameters ... all are expressions) that can change a value, it is an expression. When encountering an expression, it goes to the library and modifies the value.
alert(a); //未定义
var a=1; //在库里面a的值由未定义换成1
function fn1(){alert(2);}
alert(a); //弹出:function a(){alert(4);}
var a=1; //预解析中的a改为了1
alert(a);  //弹出1
function a(){alert(2);}//函数声明,没有改变a的值。什么也没发生。
alert(a); //继续弹出1,因为a在预处理库里面的值没有被改过。
var a=3; //预处理中a的值变为3
alert(a); //弹出3
function a(){alert(4);} //函数声明,什么也没有发生
alert(a); //继续弹出3
a(); //报错 a is not a function
The process of the above code in pre-parsing is as follows: 1) Pre-parsing: var function parameters ... read var a = 1 => a is undefined; read function a(){alert(2);} => a = function a(){alert(2);}. When a variable and a function have the same name, only the function is kept: a = function(){alert(2);}. Read var a = 3 => a is undefined; here it has the same name as the function a above, so it still keeps a = function(){alert(2);}. Read function a(){alert(4);} => a = function a(){alert(4);}. It has the same name as the previous a = function(){alert(2);}. According to the context, the later function overrides the earlier one, so pre-parsing only keeps a = function(){alert(4);}. 2) Interpret the code line by line. When an expression is read, the expression can modify the pre-parsed value. Parameters can also modify the pre-parsed value. When a function call is encountered, two things must be done: pre-parsing and parsing the code line by line. A function declaration is not an expression and does not change the value in pre-parsing.

Scope

  • Functions and variables declared inside the <script> tag are global functions and global variables (but the JS parser must finish processing one block first, and then process the other block).Top-down
  • Function: a function is also a scope. It also searches first, then executes.From inside to outside
  • Object {}
Scope chain: the process of jumping from a child scope to a parent scope
<script>
alert(a); //报错:a is not defined。因为在预解析里面压根就没有a这个东西
</script>

...

<script>
var a = 1;
</script>
<script>
alert(a); //不报错,会弹出undefined。因为预解析里面有a这个东西,但是由于执行的时候,还没有改变a的值,因此a的值为undefined
var a = 1;
</script>

...

<script>
</script>
<script>
var a = 1; //预解析里面存了a,并且a的值存为1
</script>

...

<script>
alert(a); //弹出1
</script>
var a = 1; //预处理中的全局变量a的值改为1
function fn1(){
    alert(a);
    var a = 2;
} //函数声明,什么也不做
fn1(); //遇到函数调用,开始进行预解析和逐行解读代码。在函数内,先预解析出一个局部的 a 是未定义(局部的a与全局的a一点关系都没有);然后读代码,alert(a)弹出的是undefined;然后继续执行,遇到表达式,将局部的变量a的值改为2。这时fn1的函数执行已经完成了。
alert(a); //弹出全局变量a为1
The simulation of the above code in the JS parser is as follows: 1) Pre-parsing: var function parameters... a = ... fn1 = function fn1(){ alert(a); var a=2; } 2) Parse the code line by line. Another piece of code:
var a = 1; //预处理中的全局变量a的值改为1
function fn1(){
    alert(a);
    a = 2;
} //函数声明,什么也不做
fn1(); //遇到函数调用,开始进行预解析和逐行解读代码。在函数内,没有任何函数和变量声明,因此预解析里面没东西;然后读代码,alert(a),在局部没有找到预解析的a,于是从子级作用域跳到父级作用域去找,找到了全局的a,所以弹出的是全局变量a的值1;然后继续执行,遇到表达式,将全局变量a的值改为2。这时fn1的函数执行已经完成了。
alert(a); //弹出全局变量a为2
var a = 1; //预处理中的全局变量a的值改为1
function fn1(a){ //参数本质上就是一个局部变量
    alert(a);
    a = 2;
} //函数声明,什么也不做
fn1(); //遇到函数调用,开始进行预解析和逐行解读代码。在函数内,找到参数a,因此预处理里面有个局部的a是未定义。;然后读代码,alert(a),弹出的是局部的a为undefined;然后继续执行,遇到表达式,将局部变量a的值改为2。这时fn1的函数执行已经完成了。
alert(a); //弹出全局变量a为1
var a = 1; //预处理中的全局变量a的值改为1
function fn1(a){ //参数本质上就是一个局部变量
    alert(a);
    a = 2;
} //函数声明,什么也不做
fn1(a); //遇到函数调用,开始进行预解析和逐行解读代码。在函数内,找到局部参数a,因此预处理里面有个局部的a是未定义。;然后读代码,读到第一行function fn1(a),这时有参数进来,把全局的a的值1赋给了局部变量a,这时局部变量a的值变为1,alert(a),弹出的是局部的a为1;然后继续执行,遇到表达式,将局部变量a的值改为2。这时fn1的函数执行已经完成了。
alert(a); //弹出全局变量a为1

Wanting to Get the Value Inside a Function

  • Method 1: use a global variable inside the function. Because functions can read and write global variables. See the code below:
var str = '';
function fn1(){
    var a = '大鸡腿~';
    str = a;
}
fn1();
  • Method 2: call a global function inside the function, and implement it by passing parameters. See the code below:
function fn2(){
    var a = '99999999克拉钻石';
    fn3(a);
}
fn2();
function fn3(a){ //注意这个a是fn3里面的,与fn2里面的a毫无关系
    alert(a);
}
NotesA function's curly braces form a scope; if(){} is not a scope; for(){} is also not a scope. Only scopes are pre-parsed first, then executed. The curly braces of if and for have no pre-parsing process.
alert(a); //弹出undefined。这说明if大括号中的a已经在全局就被预解析了,因此if的大括号并不是作用域
if(true){
    var a=1;
}
However, note:
alert(fn1); //在火狐浏览器里面会报错说fn1 is not defined。但是在chrome浏览器里可以正常弹出fun1函数。

if(true){
    var a = 1;
    function fn1(){
        alert(123);
    }
}
Only Firefox, when pre-parsing, cannot pre-parse functions enclosed in the parentheses of if or for. Therefore, there are compatibility issues. So if you want to define global functions or global variables, try not to put them inside the curly braces of if and for; put them outside the curly braces.
for(var i=0; i<aBtn.length; i++){
    aBtn[i].onclick = function(){
        alert(i); //弹出3。因为必须for循环全部执行完成之后,aBtn才能够点击。但是for循环执行完了,外面的i已经变成3;但是在function里面又没有i,自然找到了外面的i,也就是3.
    }
}
for(var i=0; i<aBtn.length; i++){
    aBtn[i].onclick = function(){
        alert(i); //这时候弹出的就不是3了,是undefined
        
        for(var i=0; i<aBtn.legnth; i++){
            aBtn[i].style.background = 'yellow';
        }
    }
}
for(var i=0; i<aBtn.length; i++){
    aBtn[i].onclick = function(){
        alert(i); //下面for循环的括号中的var删去了,function里面又找不到i了,所以到父级找到了i,又是个3。因此,此处会弹出3。
        
        for (i = 0; i<aBtn.length; i++){
            aBtn[i].style.background = 'yellow';
        }
    }
}

Operators

Arithmetic

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus (remainder)

Assignment

  • =
  • +=
  • -=
  • *=
  • /=
  • %=

Relational

  • <
  • >
  • <=
  • >=
  • ==
  • !=
  • ===
  • !===

Logical

  • && AND
  • || OR
  • ! NOT

Operator Precedence

  • Parentheses

Program Flow Control

Judgment

  • if
  • switch (case break default)
  • ?:

Loop

  • while
  • for

Break, Skip

  • break
  • continue

What is True, What is False

  • True: non-zero numbers, strings, true, functions, objects: [] {} elements that can be found
  • False: zero, NaN, empty string, false, null, undefined, elements that cannot be found

Function Return Value - return Explained and Applied

  • return return value: function name + parentheses (e.g., fn1()) is equivalent to getting the value after return inside that function
  • All functions have a default return value: undefined
  • Can return: numbers, strings, booleans, functions, objects (elements, [], {}, null), undefined
  • Any code after return is no longer executed
alert fn1();
function fn1(){
    return function(){
        alert(1);
    }
}
What pops up at this point is: function(){alert(1);}
alert fn1()();
function fn1(){
    return function(){
        alert(1);
    }
}
What pops up at this point is 1, which is the result of executing the anonymous function returned by return.
alert fn1()(10);
function fn1(){
    return function(a){
        alert(a);
    }
}
What pops up at this point is 10.
alert fn1(20)(10);
function fn1(a){
    return function(b){
        alert(a + b);
    }
}
What pops up at this point is 30.

arguments

fn1(1, 2, 3); //actual parameters — the parameters actually passed function fn1(a, b, c) //formal parameters — formally, the names a, b, c represent 1, 2, 3 If you don't write formal parameters, 1, 2, 3 can still be passed in, all stored inside arguments. function fn1(){ //arguments => [1, 2, 3] — the collection of actual parameters (not an array, but array-like, has length, and can also use subscripts to find the data) } When the number of function parameters cannot be determined, use arguments:
alert(sum(1,2,3));
function sum(){
    var n=0;
    for(var i=0; i<arguments.length; i++){
        n += arguments[i];
    }
    return n;
}
var a=1;
function fn2(a){ //arguments的某个数值就相当于某个形参
    arguments[0]=3;
    alert(a); //弹出3
    var a=2;
    alert(arguments[0]); //弹出2
}
fn2(a);
alert(a); //弹出1

currentStyle and getComputedStyle Application

  • getComputedStyle gets the style calculated by the computer (browser), but it is not compatible with IE6, 7, 8
  • The currentStyle method is compatible with IE6, 7, 8, but not with standard browsers
Property detection method and version detection method to solve compatibility issues between browsers ~~~ js function getStyle( obj, attr) { return obj.currentStyle ? obj.currentStyle[attr]:getComputedStyle( obj )[attr]; } ~~~Notes:
  • If you use the above method to get a compound style of an element, such as background, then do not use the above method to get it, because there are compatibility issues across different browsers. Use the above method to get a single style, and do not use it to get compound styles.
  • When using the above methods, be careful not to press extra spaces
  • When using the above methods, do not get styles that have not been set, because they are incompatible across browsers
  • Before Firefox 4.0, there was a bug: if getComputedStyle is not followed by a parameter, problems occur. So some people write getComputedStyle(obj, false); that false is to solve this bug. This bug can also be written as 0, or any other parameter. However, current Firefox browsers are relatively new, so this problem is not very common now.

Timer

setInterval

setInterval(function, milliseconds); executes repeatedly (engine)
var i=0;
function fn1(){
    document.title = i;
    i++;
}
setInterval(fn1, 1000);
Methods of event invocation
  • fn1(); direct call
  • document.onclick = fn1; event invocation
  • setInterval(fn1, 1000); function call
clearInterval
var timer = setInterval(函数, 毫秒); //重复执行
clearInterval(timer); //清除定时器
var i=0,
    timer = null;
function fn1(){
    i++;    
    document.title = i;
    
    if(i===10){
        clearInterval(timer);
    }
}
timer = setInterval(fn1, 1000);
NoteIf the timer is controlled by an event, such as a button's onclick, then you must follow one principle: close first, then open. This can avoid repeatedly setting timers by clicking the button multiple times in a row. In addition, clearInterval() can run smoothly no matter whether what is filled in is a timer, null, or undefined.

setTimeout

var timer = setTimeout(function, milliseconds); executes once (bomb) clearTimeout(timer);

Timer's Small Application (Function Encapsulation and Callback Function)

Function Encapsulation of doMove

<input id="btn1" type="button" value="走" />
<div id="div1"></div>
var oBtn1 = document.getElementById('btn1');
var oDiv = document.getElementById('div1');

oBtn1.onclick = function () {
    
    doMove ( oDiv, 'left', 12, 900, function () {
        doMove ( oDiv, 'top', 34, 500 );
    });

};

//doMove函数封装

function doMove ( obj, attr, dir, target, endFn ) {
    
    dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;
    
    clearInterval( obj.timer );
    
    obj.timer = setInterval(function () {
        
        var speed = parseInt(getStyle( obj, attr )) + dir;          // 步长
        
        if ( speed > target &amp;&amp; dir > 0 ||  speed < target &amp;&amp; dir < 0  ) {
            speed = target;
        }
        
        obj.style[attr] = speed + 'px';
        
        if ( speed == target ) {
            clearInterval( obj.timer );
            
            /*
            if ( endFn ) {
                endFn();
            }
            */
            endFn &amp;&amp; endFn();
        }
        
    }, 30);
}

function getStyle ( obj, attr ) { 
    return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; 
}

Function Encapsulation of Shake

<img id="img1" src="img/4.jpg.html" />
<img id="img2" src="img/5.jpg.html" />
window.onload = function () {
    var oImg1 = document.getElementById('img1');
    var oImg2 = document.getElementById('img2');
    
    oImg1.onclick = fnShake;
    oImg2.onclick = fnShake;
    
    function fnShake() {
        var _this = this;
        shake( _this, 'left', function(){
            shake( _this, 'top' );
        });
    }

};

function shake ( obj, attr, endFn ) {
    var pos = parseInt( getStyle(obj, attr) ); //有隐患 需要解决
    var arr = [];           // 20, -20, 18, -18 ..... 0
    var num = 0;
    var timer = null;
        
    for ( var i=20; i>0; i-=2 ) {
        arr.push( i, -i );
    }
    arr.push(0);
        
    clearInterval( obj.shake );
    obj.shake = setInterval(function (){
        obj.style[attr] = pos + arr[num] + 'px';
        num++;
        if ( num === arr.length ) {
            clearInterval( obj.shake );
            endFn &amp;&amp; endFn();
        }
    }, 50);
}

System Time Object

new Date(); //current system time object
var myTime = new Date(); //myTime的类型是object
var iYear = myTime.getFullYear(); //获得年份
Related methods (the following all return numeric types):
  • getFullYear()
  • getMonth()
  • getDate()
  • getDay()
  • getHours()
  • getMinutes()
  • getSeconds()
Notes:
  • For the month obtained with getMonth(), January starts from 0. Therefore, for example, if the current month is May, getMonth() returns 4.
  • The day of the week obtained with getDay() is a numeric value. If the current time is Sunday, it returns the number 0.

Date Object Parameters

  • Numeric form: new Date(2013, 4, 1, 9, 48, 12); //year month day hour minute second, note that the month starts from 0.
var iNow = new Date();
var iNew = new Date(2014, 10, 26, 21, 56, 0);
var t = Math.floor((iNew - iNow)/1000); 
var str = Math.floor(t/86400) + '天' +  Math.floor(t%86400/3600) + '时' + Math.floor(t%86400%3600/60) + '分' +  t%60 + '秒';
  • Days: Math.floor(t/86400)
  • Hours: Math.floor(t%86400/3600)
  • Minutes: Math.floor(t%86400%3600/60)
  • Seconds: t%60
  • String form: new Date('June 10, 2013 12:12:12');
var iNow = new Date();
var iNew = new Date('November 10, 2013 21:56:0');
var t = Math.floor((iNew - iNow)/1000); 
var str = Math.floor(t/86400) + '天' +  Math.floor(t%86400/3600) + '时' + Math.floor(t%86400%3600/60) + '分' +  t%60 + '秒';

Timestamp

getTime(); returns the number of milliseconds from January 1, 1970, 00:00:00.000 to the present

String Operations

String Retrieval Class, Encapsulating a Method to Detect Numbers

  • .lengthSpaces also count towards the length
  • .charAt()Find a substring. If nothing is written in the parentheses, the default is to find the 0th one. If it exceeds the string length minus 1, it returns empty
  • .charCodeAt()Get the Unicode encoding of the specified character. If nothing is written in the parentheses, the default is to get the Unicode value of the 0th character. The minimum in the parentheses is 0, and the maximum is the string length minus 1
  • String.fromCharCode();Return a character based on its character encoding. For example, String.fromCharCode(22937); returns the character "妙". To get multiple characters, use commas to separate different character encodings, for example: String.fromCharCode(22937, 21916); returns the two characters "妙味". 0~9 => 48~57; a~z => 97~122; A~Z => 65~90
alert(detectNum(' 1a23d456'));
function detectNum(str){
    var n = 0;
    for(var i=0; i<str.length; i++){
        n = str.charAt(i);
        if( n < 48 || n > 57 ) {
            return false;
        }
    }
    return true;
}

indexOf、lastIndexOf

  • .indexOf()Return the position of a character or string within the entire string. str.indexOf('m', 5) means starting from position 5 in the str string and searching forward for the position of character m. If indexOf() is used to search and it cannot be found, -1 is returned. It searches from left to right. If the second parameter is negative, it is treated as 0 by default.
var str = 'Example - 学的不仅是技术,更是梦想!';
var s = 'Example';
var i = 0;

for ( ; str.indexOf(s, i) != -1; ){
    alert(str.indexOf(s, i));
    i = str.indexOf(s, i) + s.length;
}

或

while(str.indexOf(s, i) != -1) {
    alert(str.indexOf(s, i));
    i = str.indexOf(s, i) + s.length;
}
  • .lastIndexOf()Search from right to left. It can also take a numeric parameter, indicating where to start searching backward from.

Comparison Class, Slicing Class

  • String size comparison compares the Unicode encoding of the character at position 0 of the strings.
  • .substring(n, m)Extract characters from the nth position to the mth position. If there is no m, it defaults to extracting to the last position. str.substring(2, 0); and str.substring(0, 2); have the same result. substring can check the size of the two parameters inside. If the later parameter is smaller than the earlier parameter, it automatically reverses the two parameters. If there are no parameters in the parentheses at all, it is equivalent to extracting from position 0 to the last position, that is, the entire string. If any parameter is negative, it is treated as 0.
  • .slice(n, m)str.slice(0, 2) and str.slide(2, 0) have different results. The latter cannot find a result because the .slice() method does not check the size of the parameters inside and swap their positions. str.slice(-2); extracts from the last position to the second-to-last position. -1 represents the last character of the string. str.slice(-4, -2); extracts the string from the fourth-to-last position to the second-to-last position.

Case Conversion, split Splitting Strings

  • .toUpperCase()Convert to uppercase
  • .toLowerCase()Convert to lowercase
  • .split()Split a string into an array. var str = 'www.miaov.com'; str.split('.'); => ["www", "miaov", "com"]; var str1 = 'leo'; str1.split(); => ['leo']; str2 = 'leo'; str2.split(''); => ["l", "e", "o"]; var str3 = '/www.miaov.com/'; str3.split('/'); => ["", "www.miaov.com", ""]; var str4 = '2013-11-29-23-07'; str4.split('-', 3); => ["2013", "11", "29"]
  • .join()Method used to join the items in an array together. var arr = ['aa', 'bb', 'cc]; arr.join(); => 'aa,bb,cc'. If nothing is written in the parentheses of .join(), it defaults to separating with commas. arr.join(''); => 'aabbcc'; arr.join('-'); => 'aa-bb-cc'

Summary of String Operations

var str = 'Example-www.example.com';

str.charAt(1); // 3
str.charCodeAt(1); // 51
String.fromCharCode(119, 51); // w3

str.indexOf('c', 3); // 4
str.lastIndexOf('o'); // 25

'1000' < '2' // true
'1000' > 2 // true

str.substring(0, 4); // Example
str.slice(-3); // .cc

str.toUpperCase(); // Example-WWW.example.com
str.toLowerCase(); // Example-www.example.com

str.split('.', 2); // ["Example-www", "example"]

var arr = ['www', 'example', 'com'];
arr.join('.'); // www.example.com

Array Operations

JSON Data Format and Syntax

var json = { name: 'leo', age: 32};
alert(json.name);

var imgData = { 
    url: ['img/1.png', 'img/2.png'],
    text: ['图片一', '图片二']
};
alert(imgData.url[1]);

var json2 = { 'name': 'miaov' }; //推荐的安全格式的写法
alert(json2.name);
alert(json2['name']);
json2.name = 'abc';
json2['name'] = '妙味'; //注意中括号里面要用引号

var arr = [{'name': 'TM', 'age': 23}, {'name': 'leo', 'age': 32}];
alert(arr[0].name);

for-in Loop, Traversing JSON

var json4 = { 'name': 'miaov', 'age': 3, 'fun': '前端开发'};
for(var attr in json4){
    alert(attr);
    alert(json4[attr]);
}

var json5 = { 
    url: ['img/1.png', 'img/2.png'],
    text: ['图片一', '图片二']
};

for(var attr in json5) {
    for(var i=0; i<json5[attr].length; i++){
        alert(json5[attr][i]);
    }
}
for-in can also iterate over object properties:
var str = '';
var num = 0;
for(var attr in window){
    str += num + '. ' + attr + ' : ' + window[attr] + '<br/>';
    num ++;
}
document.body.innerHTML = str;
Arrays can also be iterated with for-in:
var arr = ['a', 'b', 'c'];
for(var i in arr){
    alert(arr[i]);
}

Clearing Arrays and Efficiency of Clearing Arrays

// var arr = [1, 2, 3];
// var arr = new Array(1, 2, 3);

var arr = new Array(4);
alert(arr.length); // 4 在new Array()里面写了一个数字,就是定义了arr的长度
var arr = [1, 2, 3];
arr.length = 1; //数组的length属性是可写的
alert(arr);
var arr = [1, 2, 3];
arr.length = 0; //快速清空数组arr
或
arr = []; //通过重新赋值来清空数组,效率更高
var str = 'aaaaa';
str.length = 1;
alert(str); // 'aaaaa'
//字符串的length属性不可写,但是数组的length属性可写

Array Operations

Adding
  • push method: arr.push(); adds content to the last position of the array. The .push() method has a return value, which is the new length of the array.
  • unshift method: arr.unshift(); adds content to the very front of the array. The return value is the new length of the array (IE6 and IE7 do not support the return value of unshift).
Deleting
  • pop method: arr.pop(); deletes the last element of the array. The return value is the discarded value.
  • shift method: arr.shift(); deletes the first element of the array. The return value is the discarded value.
Tips
var arr = ['TM', '钟毅', '张森', '杜鹏', 'Leo'];
arr.unshift(arr.pop()); //数组变为:['Leo', '钟毅', '张森', '杜鹏', 'TM']
或
arr.push(arr.shift()); //数组变为:['钟毅', '张森', '杜鹏', 'Leo', 'TM']
splice method
  • The splice method has three functions: deletion, replacement, and addition.
var arr = ['TM', '钟毅', '张森', '杜鹏', 'Leo'];
//删除
//arr.splice(0, 1); //删掉第0位,删1个。两个参数第一个是从第几位开始,第二个是删掉几个。splice删除的时候有返回值,返回的是被删除的内容
//替换
//arr.splice(0, 1, '莫涛'); //替换第0位,替换1个,替换为'莫涛'。返回的还是删除的东西
//添加
arr.splice(1, 0, '李贤'); //在第1位那里,删除0个,添加了一个'李贤'到了第1位,'钟毅'就变成了arr[2]了。后面也可以添加多个。如果splice删除了0个,那么就没有返回值。

Array Deduplication

var arr = [1, 2, 2, 4, 2];
for ( var i=0; i<arr.length; i++ ) {
    for ( var j = i+1; j<arr.length; j++) {
        if( arr[i]==arr[j] ){
            arr.splice( j, 1 );
            j--;
        }
    }
}
sort sorting
var arr = ['c', 'd', 'a', 'e'];
arr.sort(); // 'a', 'c', 'd', 'e' 按照unicode编码排序

var arr2 = [4, 3, 5, 76, 2, 0, 8];
// arr2.sort(); // 0, 2, 3, 4, 5, 76, 8 sort默认是将数组中的每一个按照字符串来排序的,因此出现了76排在8前面的情况

// arr2. sort(function( a, b ){
    return a - b; //如果a-b返回正数,就a、b两个数字换个序。如果a-b是负数,就不换序
}) //返回数字从小到大 0, 2, 3, 4, 5, 8, 76

// arr2. sort(function( a, b ){
    return b - a;
}) //返回数字从大到小 76,, 8, 5, 4, 3, 2, 0
Other sorting methods:
  • Quick sort
  • Shell sort
  • Bubble sort
  • Merge sort
  • Selection sort
  • Insertion sort
var arrWidth = ['345px', '23px', '10px', '1000px'];
arrWidth.sort(function(a, b){
    return parseInt(a) - parseInt(b);
}); // ['10px', '23px', '345px', '1000px']
Random sorting
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
arr.sort(function(a, b){
    return Math.random(); - 0.5;
});

Random Numbers and the Reasoning Process of the Random Formula

Math.random(); returns a random number between 0 and 1 If you want to randomly return an integer between 0 and 1, you can use the rounding method: Math.round(Math.random()); // Note: Math.floor cannot be used here If you want to return a random number between 0 and 10: Math.round(Math.random() * 10); // Returns a random integer between 0 and 10 Return a random number between 20 and 100: Math.round( Math.random()*80 + 20 ); // Returns a random integer between 5 and 10 If you want to return a random integer between x and y, you can write: Math.round( Math.random() * (y - x) + x ); To return an integer from 0 to x, you can write: Math.round( Math.random() * x ); To return an integer from 1 to x, you can write: Math.ceil( Math.random() * x ); // Math.ceil() rounds upconcat methodThe concat method is used to concatenate arrays.
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = [7, 8, 9];

arr1.concat(arr2); //[1, 2, 3, 4, 5, 6] 新数组与原来数组没什么关系。
arr1.concat(arr2, arr3); //[1, 2, 3, 4, 5, 6, 7, 8, 9]
reverse methodThe reverse method reverses the positions in an array and will change the original array.
var arr1 = [1, 2, 3];
arr1.reverse();
alert(arr1); // [3, 2, 1]
var str = 'abcdef';
alert(str.split('').reverse().join('')); //'fedcba'

References

For more tutorials, you can visit our:JavaScript Tutorial。