4-14-17 JavaScript知识点总结(包括JOSN, ajax等,来源w3c)
JavaScript
也称 ECMAScript as "JavaScript"
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.
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,
Overviews:
JavaScript is a dynamic language with types and operators, standard built-in objects, and methods.
Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well.
JavaScript supports object-oriented programming.
JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.
Js's types are :
Number
String
Boolean
Symbol
(new in ES2015)Object
null
undefine
- And there are some built-in
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
, andundefined
all becomefalse.
- All other values become
true.
Boolean(''); - 例子Boolean('');// false
- Boolean(234); // true
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
}
Objects
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
Functions
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.
Global Event Attributes
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的元素中。
分几大类:
- window Event Attributes: <body>
- Form Event: almost in all html element,但主要是用在form elements.
- Keyboard Events: onkeydown
- Mouse Events: onclick ,ondblclick, 9个属性
- Drag Event(8个属性)
- Clipboard Events : oncoyp, oncut, onpaste
- Media Events:<audio> ,<img>,<video>等,但所有元素都能用。
JavaScript Can Change HTML Styless(css),Attributes, Content, Hide/Show
例子:
JavaScript Functions and Events
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.
JavaScript in <head> or <body>
Scripts can be placed in the <body>, or in the <head> section of an HTML page。也可以放在 外部文件.js ; 用<script src="myScript1.js"></script>调用。可以是部分url.
JavaScript Output
- Writing into an HTML element, using innerHTML.
- Writing into the HTML output using document.write(). should only be used for testing.
- Writing into an alert box, using window.alert(). 弹出对话框
- Writing into the browser console, using console.log() ,一般用于debugging. 比如在chrome-inspect的控制台看js的输出。
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”
JavaScript Type Operators
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"
JavaScript Function Scope
In JavaScript there are two types of scope:
- Local scope
- Global 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
Function arguments (parameters) work as local variables inside functions.
函数的参数被看作本地变量。
HTML Events
HTML元素身上发生的事情。
An HTML event can be something the browser does, or something a user does.
- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button> //this关键字,改变自己。
JS code 很长,一般event attribute用来调用function.
<button onclick="this.innerHTML = Date()">The time is?</button>
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
- Things that should be done every time a page loads
- Things that should be done when the page is closed
- Action that should be performed when a user clicks a button
- Content that should be verified when a user inputs data
- And more ...
Many different methods can be used to let JavaScript work with events:
- HTML event attributes can execute JavaScript code directly
- HTML event attributes can call JavaScript functions
- You can assign your own event handler functions to HTML elements
- You can prevent events from being sent or being handled
- And more ...
The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
判断一个变量是不是Array类型。用 instanceof方法 :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // returns true
toString():把an array 变为a string of array values(comma separated)
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
//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
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()方法
JavaScript Errors - Throw and Try to Catch
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
}
JavaScript Throws 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
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
}
JavaScript Debuggers
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
JavaScript Declarations are Hoisted
在用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(
4-14-17 JavaScript知识点总结(包括JOSN, ajax等,来源w3c)的更多相关文章
- JavaScript知识点总结
JavaScript学习总结1.JavaScript是作用于网络和HTML的一个编程语言.2.JavaScript代码必须放在<script></script>标签之间,Jav ...
- JavaScript知识点整理(一)
JavaScript知识点(一)包括 数据类型.表达式和运算符.语句.对象.数组. 一.数据类型 1) js中6种数据类型:弱类型特性 5种原始类型:number(数字).string(字符串).bo ...
- JavaScript -- 知识点汇总
js语法 1. javascript数据类型 JavaScript拥有动态类型.这意味着相同的变量可用作不同的类型:有 字符串,数字, 布尔值, 对象, 数组,Undefined和Null 对象: v ...
- 介绍 14 个 JavaScript 的框架和库
Javascript 得到了众多的技术领导者的拥护和支持,其中一位就是 WordPress 的作者 Matt Mullenweg , 他表示 WordPress 开发者 应该学习 JavaScript ...
- 8年javascript知识点积累
08年毕业就开始接触javascript,当时是做asp.net发现很多功能用asp.net控件解决不了,比如checkbox单选,全选问题,自动计算总价问题,刷新问题,等等.那时感觉javascri ...
- javascript知识点积累
8年javascript知识点积累 08年毕业就开始接触javascript,当时是做asp.net发现很多功能用asp.net控件解决不了,比如checkbox单选,全选问题,自动计算总价问题, ...
- Javascript:必须知道的Javascript知识点之“单线程事件驱动”
heiboard: Javascript:必须知道的Javascript知识点之“单线程事件驱动”
- 基数排序的可复用实现(C++11/14/17/20)
基数排序,是对整数类型的一种排序方法,有MSD (most significant digit)和LSD (least significant digit)两种.MSD将每个数按照高位分为若干个桶(按 ...
- JavaScript 在函数中使用Ajax获取的值作为函数的返回值
解决:JavaScript 在函数中使用Ajax获取的值作为函数的返回值,结果无法获取到返回值 原因:ajax默认使用异步方式,要将异步改为同步方式 案例:通过区域ID,获取该区域下所有的学校 var ...
随机推荐
- Java基础语法(基本语句)
Java基础语法 标识符在程序中自定义的一些名称.由26个英文字母大小写,数字:0-9符号:_&组成定义合法标识符规则:1. 数字不可以开头2. 不可以使用关键字Java中 ...
- Spring,Struts2,MyBatis,Activiti,Maven,H2,Tomcat集成(四)——Activiti集成
1.添加Activiti Maven依赖: <!-- ==============================activiti=========================== --&g ...
- linux常用命令:yum 命令
用于添加/删除/更新RPM包,自动解决包的依赖问题以及系统更新升级. 1.命令格式: yum [参数] [软件名]2.命令功能: 功能: yum提供了查找.安装.删除某一个.一组甚至全 ...
- mustache多次渲染和多个赋值
mustache多次渲染和多个赋值, html页面的script标签中的代码,设置多个键: <!-- 项目列表 --> <script type="text/x-templ ...
- pycharm中内看内建函数的定义
鼠标方法在内建函数上,Ctrl+B,看内建函数的定义 如果想要看内置函数的具体实现细节,可以到python的lib目录下C:\Python27\Lib\,或者python的官网上 如果要看非内建的函数 ...
- Java系列笔记(0) - 目录和概述
笔者在开发过程中发现自己基础太薄弱,读书时除了系统学习了一下Java的基础语法和用法.一点简单的数据结构和设计模式之外,再无深入系统的学习,而工作中的学习也是东晃一枪西晃一枪,不够扎实和系统.想到一个 ...
- C站投稿映兔源的方法
(因映兔源也不太稳定了,所以不建议映兔上传,正在找其他视频源代替映兔,另外等待C站大大们的webbt源)(20180226) 测试换文件格式后会不会失效,能坚持几天?http://www.cnblog ...
- 02:zabbix-agent安装配置 及 web界面管理
目录:Django其他篇 01: 安装zabbix server 02:zabbix-agent安装配置 及 web界面管理 03: zabbix API接口 对 主机.主机组.模板.应用集.监控项. ...
- C++ 单例模式(转载)
转载:http://www.cnblogs.com/cxjchen/p/3148582.html 转载:http://blog.csdn.net/hackbuteer1/article/details ...
- python字符串格式化之format
用法: 它通过{}和:来代替传统%方式 1.使用位置参数 要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表 ...