Get started with Programming

Javascript中的保留字,但是大部分却没在这个语言中使用。undefined,NaN,Infinity也应该算保留字。

abstract
boolean break byte
case catch char class const continue
debugger default delete do double
else enum export extends
false final finally float for function
goto
if implements import in instanceof int interface
long
native new null
package private protected public
return
short static super switch synchronized
this throw throws transient true try typeof
var volatile void
while with

Reserved Words

confirm("I am ok");
prompt("Are you ok?");

"text".length
console.log();

> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
=== Equal to
!== Not equal to

"text".substring(0, 2);

confirm("I am ready to play!");
var age = prompt("What's your age");
if (age < 13) {
console.log("You're allowed to play but you take no responsibility.");
} else {
console.log("Play on!");
} console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'"); console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'"); var userAnswer = prompt("Do you want to race Bieber on stage?"); if (userAnswer === "yes") {
console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!");
} else {
console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
} var feedback = prompt("Could you give a rate?");
if (feedback > 8) {
console.log("Thank you! We should race at the next concert!");
} else {
console.log("I'll keep practicing coding and racing.");
}

Prompt

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice); var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins";
}
} else if (choice1 === "paper") {
if (choice2 === "scissors") {
return "scissors wins";
} else {
return "paper wins";
}
} else {
if (choice2 === "paper") {
return "scissors wins";
} else {
return "rock wins";
}
}
} compare(userChoice, computerChoice);

Rock-Paper-Scissors

var slaying =  true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0; while (slaying) {
if (youHit) {
console.log("You hit the dragon and did " + damageThisRound + " damage!");
totalDamage += damageThisRound; if (totalDamage >= 4) {
console.log("You did it! You slew the dragon!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon burninates you! You're toast.");
slaying = false;
}
}

Slaying Dragon

Objects in JS

var phonebookEntry = {};

phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';
phonebookEntry.phone = function() {
console.log('Calling ' + this.name + ' at ' + this.number + '...');
}; phonebookEntry.phone();

Create an Object

var me = {name: "Dave Obama", age: 55};

Create an Object

var me = new Object();
me.name = "Dave Obama";
me["gender"] = "male";
me.age = 55;

Create an Object

var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(408) 555-5555",
address: ['1 Infinite Loop','Cupertino','CA','95014']
}; var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
}; var search = function(name) {
for(var prop in friends) {
if(friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
}
}; list(friends);
search("Steve");

Contact List

Introduction to Objects

dot notation => new Object()

bracket notation => { }

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge; // change bob's age to 50 here
bob.setAge(50);

The "this" keyword

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
return this.sideLength * 4;
};
// help us define an area method here square.calcArea = function() {
return this.sideLength * this.sideLength;
}; var p = square.calcPerimeter();
var a = square.calcArea();

The "this" keyword

function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
} // now we can easily make all of our rabbits var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy"); rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();

Constructor

Why is using “for…in” with array iteration such a bad idea?

function Circle (radius) {
this.radius = radius;
this.area = function () {
return Math.PI * this.radius * this.radius; };
// define a perimeter method here
this.perimeter = function () {
return Math.PI * this.radius * 2;
}
};

Define methods in Constructor

// complete these definitions so that they will have
// the appropriate types
var anObj = { job: "I'm an object!" };
var aNumber = 42;
var aString = "I'm a string!"; console.log( typeof anObj ); // should print "object"
console.log( typeof aNumber ); // should print "number"
console.log( typeof aString ); // should print "string" var myObj = {
// finish myObj
name: "Obama"
}; console.log( myObj.hasOwnProperty('name') ); // should print true
console.log( myObj.hasOwnProperty('nickname') ); // should print false var suitcase = {
shirt: "Hawaiian"
}; if (suitcase.hasOwnProperty("shorts")) {
console.log(suitcase.shorts);
} else {
suitcase.shorts = "Hello";
console.log(suitcase.shorts);
} var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
}; for (var prop in nyc) {
console.log(prop);
console.log(nyc[prop]);
}

typeof hasOwnProperty

function Dog (breed) {
this.breed = breed;
} // here we make buddy and teach him how to bark
var buddy = new Dog("Golden Retriever");
buddy.bark = function() {
console.log("Woof");
};
buddy.bark(); // here we make snoopy
var snoopy = new Dog("Beagle");
// we need you to teach snoopy how to bark here
snoopy.bark = function() {
console.log("abc");
}
// this causes an error, because snoopy doesn't know how to bark!
snoopy.bark();

Methods just for one object

function Dog (breed) {
this.breed = breed;
}; // here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {
console.log("Woof");
};
buddy.bark(); // here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();

Prototype

//Example of inheriting methods
// the original Animal class and sayName method
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
}; // define a Penguin class
function Penguin(name) {
this.name = name;
this.numLegs = 2;
} // set its prototype to be a new instance of Animal
Penguin.prototype = new Animal(); //Example of inheriting properties
function Penguin(name) {
this.name = name;
this.numLegs = 2;
} // create your Emperor class here and make it inherit from Penguin
function Emperor(name) {
this.name = name;
} Emperor.prototype = new Penguin();
// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("Dave");
console.log(emperor.numLegs);

Inheritance

var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
}; // print hello in the 3 different languages
for (var prop in languages) {
if (typeof languages[prop] === "string")
console.log(languages[prop]);
}

Another typeof example

// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType); // now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");
console.log(hasOwn);

Object.prototype

function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
} var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10); // Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("Dave", 20); var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount: function(employee) {
this.total *= (100 - employee.discountPercent)/100;
} }; cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me); // Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));

Cash Register

var myObject = {value: 10};
var add =function (a, b) {return a + b;}; // “this” is not whomever calls the object. myObject.double = function () {
var that = this; // Workaround.
var helper = function () {
that.value = add(that.value, that.value);
};
helper();
// Invoke helper as a function.
};
// Invoke double as a method.
myObject.double();
console.log(myObject.value);

This

var add = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw {
name: 'TypeError',
message: 'add needs numbers'
};
}
return a + b;
} var try_it = function () {
try {
add("seven");
} catch (e) {
console.log(e.name + ': ' + e.message);
}
} try_it();

Try Catch

var myObject = (function () {
var value = 0;
return {
increment: function (inc) {
value += typeof inc === 'number' ? inc : 1;
},
getValue: function () {
return value;
}
};
}()); myObject.increment(45);
myObject.increment(25);
console.log(myObject.getValue());

Return an Object containing methods

var fade = function (node) {
var level = 1;
var step = function () {
var hex = level.toString(16);
node.style.backgroundColor = '#FFFF' + hex + hex;
if (level < 15) {
level += 1;
setTimeout(step, 100);
}
};
setTimeout(step, 100);
}; fade(document.body); <html>
<body>
<pre>
<script src="program.js"></script>
</pre>
</body>
</html>

Fade

var i, word,
text = "This oracle of comfort has so pleased me, " +
"That when I am in heaven I shall desire " +
"To see what this child does, " +
"and praise my Constructor."; var words = text.toLowerCase().split(/[\s,.]+/);
var count = {};
for (i = 0; i < words.length; i += 1) {
word = words[i];
if (typeof count[word] === 'number') { // Do not use if (count[word]) here, because count inherited “constructor” from Object. += does concatenation when its operators are not numbers.
count[word] += 1;
} else {
count[word] = 1;
}
} for (var prop in count) {
console.log(prop + ": " + count[prop]);
}

Javascript Notes的更多相关文章

  1. JavaScript技巧手冊

    js小技巧 每一项都是js中的小技巧,但十分的有用! 1.document.write(""); 输出语句  2.JS中的凝视为//  3.传统的HTML文档顺序是:documen ...

  2. Dreamweaver 扩展开发: Calling a C++ function from JavaScript

    After you understand how C-level extensibility works in Dreamweaver and its dependency on certain da ...

  3. Android Weekly Notes Issue #227

    Android Weekly Issue #227 October 16th, 2016 Android Weekly Issue #227. 本期内容包括: Google的Mobile Vision ...

  4. JavaScript系列文章:自动类型转换

    我们都知道,JavaScript是类型松散型语言,在声明一个变量时,我们是无法明确声明其类型的,变量的类型是根据其实际值来决定的,而且在运行期间,我们可以随时改变这个变量的值和类型,另外,变量在运行期 ...

  5. JavaScript系列文章:变量提升和函数提升

    第一篇文章中提到了变量的提升,所以今天就来介绍一下变量提升和函数提升.这个知识点可谓是老生常谈了,不过其中有些细节方面博主很想借此机会,好好总结一下. 今天主要介绍以下几点: 1. 变量提升 2. 函 ...

  6. 前端知识杂烩(Javascript篇)

    1. JavaScript是一门什么样的语言,它有什么特点?2.JavaScript的数据类型都有什么?3.请描述一下 cookies,sessionStorage 和 localStorage 的区 ...

  7. JavaScript中reduce()方法

    原文  http://aotu.io/notes/2016/04/15/2016-04-14-js-reduce/   JavaScript中reduce()方法不完全指南 reduce() 方法接收 ...

  8. 富文本编辑器防止xss注入javascript版

    富文本编辑器:ueditor 其实富文本编辑器已经有防止xss注入功能,但是你服务端程序在接收的时候在做一次转义,否则有可能然后前端验证直接提交数据导致被xss攻击. 为了节省后端程序开销则在前端 显 ...

  9. 大型 JavaScript 应用架构中的模式

    原文:Patterns For Large-Scale JavaScript Application Architecture by @Addy Osmani 今天我们要讨论大型 JavaScript ...

随机推荐

  1. 微信小程序-实现分享(带参数)

    微信小程序分享功能的实现方法有两种: 第一种 在page.js中实现onShareAppMessage,便可在小程序右上角选择分享该页面 onShareAppMessage: function () ...

  2. django 学习之model操作(想细化)

    一.Field选项 null=True 数据库为空 blank=True admin相关为空 choices:choices意味着静态数据的变化不会太大. db_column: 用于此字段的数据库的列 ...

  3. InlineModelAdmin

    参考博客:https://www.cnblogs.com/linxiyue/p/4074562.html

  4. css遮罩层

    父元素:position:fixed; 让子元素居中对齐:position:absolute;top:0;bottom:0;left:0;right:0;margin:auto; <style& ...

  5. Android Studio 1.1.0 “关联源码” 或者“导入源码” ,又或者插件包

    其实这博文是废话!为什么呢? 1.如果自己的SDK没有更新相应当前操作版本的source的话,相应的v4,v7等等的源码都不会自动导入的. 其实Android Studio自身就已经会去检测你当前SD ...

  6. Zynq开发之HLS

    Zynq开发之HLS 由 FPGA菜鸟 于 星期三, 06/28/2017 - 11:53 发表 HLS简介 HLS(High Level Synthesis)即高层次综合,不同于以往的FPGA逻辑开 ...

  7. [na]交换机接口文档

    文档中有一些数据包等附件,pdf不能看,去这里.http://note.youdao.com/share/?id=5319680eb0c8b9c3f8fefd157534fd90&type=n ...

  8. Angular 4.0从入门到实战

    AngularJS 优点 模板功能强大丰富,并且是声明式的,自带了丰富的Angular指令: 是一个比较完善的前端MVC框架,包含模板,数据双向绑定,路由,模块化,服务,过滤器,依赖注入等所有功能: ...

  9. c++ STL map 结构体

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候 ...

  10. git无法提交,存在未提交的修改,在重新合并前或者撤销更改

    其实我没有修改.但是却无法同步. 解决方法: 1.在vs里, 打开git的命令提示符 2.输入一下命令: git stashgit stash pop 3.然后再git checkout试试,然后提示 ...