JavaScript javascript
也称 ECMAScript as "JavaScript" php
It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms机制 for communicating with the outside world. css
The most common host environment is the browser, but JavaScript interpreters(翻译,解释程序) can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB,html
Overviews:前端
JavaScript is a dynamic language with types and operators, standard built-in objects, and methods.java
Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. node
JavaScript supports object-oriented programming. web
JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.ajax
Js's types are :chrome
Number
String
Boolean
Symbol
(new in ES2015)Object
null
undefine
Error
types as well
Numbers:
parseInt()至关于to_i 。 parseInt('123',10);// 123,第二个参数是转换为几进制,默认10进制。相似的还有parseFloat()
特殊值: Infinity, -Infinity. 表明无穷数。 1/0; // Infinity
isFinite(1/0);// false, 是有限的吗?不是。
Strings
'hello'.length;// 5
String像对象,可看成对象使用一些方法。
'hello'.charAt(0); // "h"
'hello, world'.replace('hello','goodbye'); // "goodbye,world"
'hello'.toUpperCase(); // "HELLO"
othertypes
false
, 0
, empty strings (""
), NaN
, null
, and undefined
all become false.
true.
Boolean('');
Variables
New variables in JavaScript are declared using one of three keywords: let
, const
, or var
.
let allows you to declare block-level variables.只能在块内用。
for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
// myLetVariable is only visible in here }
const 就是常量 const Pi =3.14;以后就不能改变了,不然报错。Ruby是用所有大写字母表示常量。
var 是变量,var name = ''tom";
Operations:
和Ruby相似,+=,-= ,但多了 ++ ,—— 用法。
另外能够这么写 :若是有字符串,就合并为字符串。
'3'+4+5; // "345"
3+4+'5'; // "75"
<
, >
, <=
and >=
. 用于比较数字和字符串均可以。
== : 1 == true; //true
===同时比较type: 1 === true; // false
Control structures
if
var name = 'kittens';
if (name == 'puppies') {
name += ' woof';
} else if (name == 'kittens') {
name += ' meow';
} else {
name += '!';
}
name == 'kittens meow';
while和do..while
while (true) {
// an infinite loop!
}
var input;
do {
input = get_input();
} while (inputIsNotValid(input));
for循环3种。
for (var i = 0; i < 5; i++) {
// Will execute 5 times
}
JavaScript also contains two other prominent for loops: for
...of
for (let value of array) {
// do something with value
}
and for
...in
:
for (let property in object) {
// do something with object property
}
JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to: Hashes in Perl and Ruby.
"name" 是string类,value是任意类。两种写法:
var obj = new Object(); //相似Ruby obj = Class.new()
And:
var obj = {};
var obj = {
name: 'Carrot', details: { color: 'orange', size: 12 } };
Attribute access can be chained together:
很像obj.method,而且能够用chain式写法;也相似hash类的写法。
obj.details.color; // orange
obj['details']['size']; // 12
Function 特殊的object
相似Ruby中的类,其实js和Ruby都是everything is object.
function Person(name, age) {
this.name = name;
this.age = age;
}
// Define an object
var you = new Person('You', 24);
// We are creating a new person named "You" aged 24.
obj.name = 'Simon'; 等同于 obj["name"] = "Simon";用这种写法✅好
var name = obj.name;
(后面还有Function的知识)
Array也是特殊的对象
var a = new Array(); //相似Ruby, a = Array.new
a[0] = 'dog';
a[1] = 'cat';
a[2] = 'hen';
a.length; // 3 length是个方法
简单写法:
var a = ['dog', 'cat', 'hen']; // Ruby , a = ['dog', 'cat', 'hen']
a.length; // 3
Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:
function add(x, y) {
var total = x + y;
return total;
}
A JavaScript function can take 0 or more named parameters.
The function body can contain as many statements as you like and can declare its own variables which are local to that function.
The return
statement can be used to return a value at any time. If no return statement is used (or an empty return with no value), JavaScript returns undefined
.
add(); // NaN // You can't perform addition on undefined
You can also pass in more arguments than the function is expecting:多余的参数被忽视掉
add(2, 3, 4); // 5 // added the first two; 4 was ignored
例子1:
function avg() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return{ sum / arguments.length };
}
add(2, 3, 4, 5); // 3.5
例子1的简化写法,例子2,使用rest parameter operator和for...of循环:
function avg(...args) {
var sum = 0;
for(let value of args) {
sum += value;
}
return sum / args.length;
}
avg(2,3,4,5); //3.5
例子2的 重写法
function avgArray(arr) {
var sum = 0;
for(var i = 0, j = arr.length; i < j; i++) {
sum += arr[i];
}
return sum / arr.length;
}
avgArray([2,3,4,5]); // 3.5
javascript已经内置了avg(...numbers)方法
Custom objects
javasscript用函数做为class ,也做为方法。函数自己就是对象。
//相似一个类,能够定义对象
function makePerson(first, last) {
return {
first: first, last: last
};
}
//也相似一个方法 ,传递一个参数,返回结果。
function personFullName(person) {
return person.first + ' ' + person.last;
}
function personFullNameReversed(person) {
return person.last + ', ' + person.first;
}
//函数自己就是object
s = makePerson('Simon', 'Willison');
personFullName(s); // "Simon Willison"
personFullNameReversed(s); // "Willison, Simon"
能够用更好的写法:
function makePerson(first, last) {
return {
first: first,
last: last,
fullName: function() {
return this.first + ' ' + this.last;
},
fullNameReversed: function() {
return this.last + ', ' + this.first;
}
};
}
s = makePerson('Simon', 'Willison');
s.fullName(); // "Simon Willison"
s.fullNameReversed(); // "Willison, Simon"
the this
keyword. Used inside a function, this
refers to the current object.
this后面用.或[],便表示当前对象,若是没有使用则是全局对象。
用new的写法和this关键字来改进上面的写法:去掉了return{};
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = function() {
return this.first + ' ' + this.last;
};
this.fullNameReversed = function() {
return this.last + ', ' + this.first;
};
}
var s = new Person('Simon', 'Willison');
new关键字代替了return。
Functions that are designed to be called by new
are called constructor functions.
可是,嵌套的函数写法,尤为是有好几个函数,看起来很丑:改进:
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
看起来好多了,可是使用prototype方法,能够随时根据须要定义新的函数,更加方便:
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.fullName = function() {
return this.first + "" + this.last;
}
Person.prototype.fullNameReversed = function() {
return this.last + ", " + this.first;
}
相似于类的继承,js里面,若是声明了一个string变量,使用String.prototype定义的方法,也能够用在这个变量上。由于string对象继承了String的方法。
一样,用prototype能够从新定义js的内置方法。
《Ruby元编程2》--239覆写方法:prepend,refinement细化,环绕别名。
镶嵌函数做用域,外部定义的变量,内函数能够用,但内函数定义的变量,外面不能用。
Closures
function makeAdder(a) {
return function(b) {
return a + b;
};
}
var x = makeAdder(5);
var y = makeAdder(20);
x(6); // ? 11
y(7); // ? 27
解释:
Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters.
只要传进参数,函数初始化一个做用域对象,这个对象用来储存全部在函数中建立的本地变量。
因此当makeAdder() 被调用时,一个scope obj就被建立了,里面有一个property: a 。而后makAdder() 返回一个新建立的函数,这样x里面就储存了a。
A Closure is the combination of a function and the scope object in which it was created. 闭包能够储存state,所以闭包经常被用来取代对象。
闭包的原理详述(英文)https://stackoverflow.com/questions/111102/how-do-javascript-closures-work
W3C.
HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.能够把这些属性加到html的元素中。
分几大类:
JavaScript Can Change HTML Styless(css),Attributes, Content, Hide/Show
例子:
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
Scripts can be placed in the <body>, or in the <head> section of an HTML page。也能够放在 外部文件.js ; 用<script src="myScript1.js"></script>调用。能够是部分url.
var x, y; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
Js使用lower camel Case,首字母小写的驼峰写法。
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
var carName; //这个被声明但没有赋值,因此自动给一个值 undefined。
JS再声明没有任何效果。
var x = "5" + 2 + 3; //“523”
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4]
// Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
若是调用函数但没有(),则返回函数定义自己。
若是调用函数,参数为空,则返回NaN. (not a number)
判断NaN 函数 isNaN(), NaN是一个数字, typeof Nan; // returns "number"
In JavaScript there are two types of scope:
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
若是你分配一个值给一个未声明的变量,这个变量自动成为全局变量,最好别这么用。
(Ruby 不须要声明。 全局变量$name)
Function arguments (parameters) work as local variables inside functions.
函数的参数被看做本地变量。
HTML元素身上发生的事情。
An HTML event can be something the browser does, or something a user does.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<
element
event
=
'
some JavaScript
'
>
<button onclick="this.innerHTML = Date()">The time is?</button> //this关键字,改变本身。
JS code 很长,通常event attribute用来调用function.
<button onclick="this.innerHTML = Date()"> The time is? </button>
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
Many different methods can be used to let JavaScript work with events:
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
判断一个变量是否是Array类型。用 instanceof方法 :
var fruits = [ "Banana" , "Orange" , "Apple" , "Mango" ];toString():把an array 变为a string of array values(comma separated)
var fruits = [ "Banana" , "Orange" , "Apple" , "Mango" ];//Banana,Orange,Apple,Mango
join(), pop(), push(), shift(),unshift()
concat() method creates a new array by merging (concatenating) existing arrays:slice(1):去掉第几个元素。
sort():按照字母顺序排序
reverse(), 反向排列元素
break 和 continue
The continue statement (with or without a label reference) can only be used to skip one loop iteration.
The break statement, without a label reference, can only be used to jump out of a loop or a switch.
With a label reference, the break statement can be used to jump out of any code block:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
break list; //直接跳出这个块了。
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}
The constructor property returns the constructor function for all JavaScript variables
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]}
Js也有RegExp,和Ruby里用法同样,多了个test()方法
The try statement lets you test a block of code for errors (点击连接,案例)
The catch statement lets you handle the errors.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch , regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
When an error occurs, JavaScript will normally stop and generate an error message.
JavaScript will throw an exception (throw an error).
JavaScript will actually create an Error object with two properties: name and message.
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
use console.log() to display JavaScript values in the debugger window
debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.
在chrome的检查器中自动会弹到debugger关键字。
Hoisting: lift sth up
在用js编译代码的时候,先使用变量,而后再声明变量是能够的,由于js会默认把全部声明放到当前script/function的顶部,执行的时候仍是先声明后使用。
不过(initialize)在声明的同时赋值,如 :var x = 5; 则不会被hoist。
把Declare Variables 放到顶部是好的作法。
Style Guide 代码规范
Always use 4 spaces for indentation of code blocks:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Avoid global variables, avoid new, avoid ==, avoid eval()
The === operator forces comparison of values and type:用来代替==
在js, 0表明false,
var x = 0;
if (x = 0) //false
floats不会很是精确。
最好:arrays use numbered indexs; object use named indexs(👆提过)
相关预习:
HTML Input Types:
<input type="text">
defines a one-line text input field
<input type="password">
defines a password field
<input type="submit">
defines a button for submitting form data to a form-handler.
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form's action
attribute:
<input type="submit">
defines a button for submitting form data to a form-handler.
<input type="reset">
defines a reset button that will reset all form values to their default values
<input type="radio">
defines a radio button.<input type="checkbox">
defines a checkbox.
<input type="button" onclick="alert('hello')" value='Click me'>
defines a button:
HTML5还定义了一堆其余的类型: (都是前端,用C写的须要新的浏览器支持。)
HTML Input Attributes
The size
attribute specifies the size (in characters) for the input field框:
The value
attribute specifies the initial value for an input field:
he maxlength
attribute specifies the maximum allowed length for the input field:(这个属性不支持反馈feedback,必须提醒用户)
JavaScript Form Validation
若是表格myForm的fname输入框的值是空的,则提示消息。
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
表格在提交的时候调用JS function:
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
5 有了新的html验证原理:约束性验证,包含3部分:
CSS Pseudo Selectors:A pseudo-class is used to define a special state of an element:如:20多个伪类
a.highlight:hover {
color: #ff0000;
}
须要配合HTML的约束,一块儿使用。功能很是齐全的对输入进行🚫。
Methods :
Property | Description |
---|---|
checkValidity() | Returns true if an input element contains valid data. |
setCustomValidity() | Sets the validationMessage property of an input element. |
Properties:
Property | Description |
---|---|
validity | Contains boolean properties related to the validity of an input element. |
validationMessage | Contains the message a browser will display when the validity is false. |
willValidate | Indicates if an input element will be validated. |
还包括了 The validity property (Js的内置函数)of an input element contains a number of properties related to the validity of data(很是全面)
Javascript HTML DOM EventLIstener
这个方法附加了一个对指定元素的event事件。
你能够增长多个事件给一个元素。
你能够增长多个相同类型的事件给一个元素。
这个方法默认是bubbing的,即嵌套的结构<div><p>..</p></div>:
当两个元素同时绑定了click事件,点击了<P>会先激发它的event, 而后再激发<div>的event。
也能够选择capture,即从外到内的捕捉event。
addEventListener() method, removeEventListener()
结构:
element.addEventListener(event, function, useCapture);
useCapture是布林值,设置true就是capture触发方式。
删除事件监听的实例: 点击查看
用来区分一个页面不一样元素的助手:能够配合getElementById, Class, TagName, querySelectorAll.
节点包括element,attribute, text(就是实际内容) , comment(就是注释).
All nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be nodified or deleted.
除了root节点,每一个节点都只有一个父节点, 能够有不少子节点。
Siblings(brothers) are nodes with the same father.
节点的导航:
等价关系: node.nodeValue
document.getElementById("id02").innerHTML
等同于
document.getElementById("id01").firstChild.nodeValue;
document.getElementById('id01').childNodes[0].nodeValue;
document.body能够获得<body>内的全部nodes
document.documentElement能够得知所有的文档,包括<head>, <body>
nodeName特性:(只读)
元素的nodeName就是它的tag(字母大写),好比<p>的nodeName是 P , <h1>的nodeName是 H1
属性节点的nodeName就是属性名字。
text node的nodeName是#text
document node 的nodeName是#document
nodeValue特性
元素的nodeValue自定义
text node的nodeValue是它自己,
属性的nodeName是属性的value
nodeType特性 (只读)
元素的nodeType都是 1 。
text node的nodeType是 3
使用节点对要操做的元素定位:增长,指定位置插入,移除,替换。
1.增长一个<p>: 要增长先要建立createElement('element')
2.指定位置插入:
father-element.insertBefore(this-element, sibling-element)
在某个做为父亲的元素内部,插入一个元素,这个元素的位置依据它后面的兄弟元素判断。
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para, child); //插在div内部的第一个位置。
</script>
3.删除Removing Existing element(一些浏览器不支持)
parent.removeChild(this-child)
4.替换 Replacing element
parent.replaceChild(this, sipling-child);
getElementsByTagName() method returns an HTMLCollection object.
使用length方法获得集合中对象的数量,
能够用循环对集合中的对象进行一一处理。(这不是array)
还有getElementsByClassName()
JavaScript HTML DOM Node LIsts
从一个document中提取的nodes的集合(list)。(点击查看案例)
和NodeList Object功能相似:
querySelectorAll(), childNodes().
可使用length方法。可使用循环(这不是array)。
二者的区别(8,9):
JavaScript Object Notation
JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.
JSON format is text only, written with JS object notation
Why use JSON?
由于是test格式数据,容易被服务器传输和被任意编程语言储存。
JSON.parse() and JSON.stringify()
因此,若是从一个服务器接收数据,用JSON格式,你能够用它像其余JS object同样。
JSON Syntax Rules(和js类似,js程序能够轻松把JSON数据转化为js object)
一个常常的使用json的地方是从web服务器读取数据而后在网页显示数据:
Sending Data: JSON.stringify()
数据库中的JavaScript object -> 转化为JSON的text数据格式 ->发送给a server
Receiving Data:JSON.parse()
接收到JSON 格式的data(就是字符串),->转化为JavaScript Object
Storing Data and Retrieving Data:
储存:localStorage.setItem("要储存的数据的名字", myJSON);
取出:localStorage.getItem("要取出的数据的名字")
JSon vs XML https://www.w3schools.com/js/js_json_xml.asp
XML用起来更麻烦,转化为JS也麻烦。JSON转化更快。
对于AJAX applications, JSON is faster and easier than XML:
JSON 的 value只能是string ,number, boolean, null, array, 和 an object(JSON object) ,不能是函数和undefined;
JSON From the Server
只要服务器端的response是用JSON格式写的,就能够用JSON.parse转化为a JS object.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true); // 也能够是php文件:"demo_file.php"
xmlhttp.send();
知识点很全的案例:
https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table_dynamic
The Keystone of AJAX is the XMLHttpRequest Object(关键之石,中文擎天博玉柱的意思)
用于在后台和服务器交互数据,意味着局部加载网页,而不是reload整个页面。
variable = new XMLHttpRequest();
The XMLHttpRequest() Object又8个方法,6个properties.
6个 properties:
4. responseXML: Returns the response data as XML data.
5. status: Returns the status-number of a request.(所有状态码信息),这是一系列的数字,用来表示web server 和 browser之间的交互状况。
- 200: 'ok' 标准的反馈,你的请求已经处理成功!
- 403: "Forbidden", 请求收到,可是拒绝给你反馈。
- 404: "Not Found" ,服务器告诉浏览器请求还没收到。
8个 methods:
实例:
创建请求对象:
用onreadystatechange定义一个函数: 若是请求收到服务器的一个回答,则执行函数 (请求对象等待服务器处理请求)
若是readyState是4(请求完成而且反馈也传回了)而且status是200(http反馈的详细信息用数字进行区分,这里是反馈给浏览器请求成功了)则。。。
设置请求对象的请求格式,是获取信息仍是传输更新的信息, 链接到url(文件),同步/异步
通常是异步true, 这样JS不须要等待回复,先执行其余scripts
设定更新数据的头部,
xhttp.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
口令:发射!
AJAX - Server Response
The onreadystatechange Property:
用于定义一个等待执行的函数 。每当readyState特性变化时,这个函数就执行一次。
由于readyState从1-4变化四次,因此函数总共执行4次,
readyState: Holds the status of the XMLHttpRequest. 表示请求处理的状况,5个步骤。
0. request not initialized
status property: Holds the status of the object. 表示服务器处理请求对象的结果状态。用数字表示。信息100-103,成功200-206,Redirection:300-308, Client Error:400-417, Server Error 500-511.
The getAllResponseHeaders() Method
从服务器返回全部的头部信息,如length, server-type, content-type, last-modified等10几种。
The getResponseHeader() Method返回指定的头部信息
一个时候xml和jS 的例子:AJAX XML Example
https://www.w3schools.com/js/js_ajax_xmlfile.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_xml2
数据的获取是调用请求对象的特性responseXML,而后使用getElementByTagName和DOM 的node节点得到想要显示到浏览器页面的数据。
https://www.w3schools.com/js/cd_catalog.xml
AJAX能够和php,asp应用交互,能够和数据库交互。
1. 显示整个表格
2. 显示其中一组数据
3.再加上两个函数用于显示上下条数据。