Javascript 学习笔记1

Javascript 学习笔记1

所有有“注意”的地方都是曾犯过的错误,要Ctrl+F搜索出来反复强化。

了解几个固有功能:

   1. myString.substring(1,2);	//extract substring
   2. confirm("Do you want to continue?"); //ask user for confirm
   3. prompt("What's your age?");	//ask user for type in
   4. console.log("Hello worldd!");	//Print out the content
   5. var myVariable; 			//declare a variable
   6. declare a function:
         //声明一个函数:
   var myFunktion = function(input_num){
   var val = input_num/3;
   console.log(val);
   };


  // use myFunktion:
  myFunktion(6);


  //又如:========
  var greeting = function(name){
    console.log("Great to see you," + " my dear " + name);
    };
  greeting("sonictl");


===========================
    7. 声明一个空数组:
       var hits = [];

    8. 关于数组和string的访问: 
            var myName = "Emily"; //myName[0] = "E"  用数组的视角访问String中的字母
            var StrArr = ["Bear","Panda"];  //StrArr[0] = "Bear"  用数组的视角访问数组中的成员
    9. 关于text.substring(i,i+length) 犯的错误: text.substring(i,length); ×
 
    10.  var i = 5;
          do{
            i--;
            }
         while(i)    //this is how "do ... while... " works.

    11.  switch(input){  
             case "0":
                console.log("No dog");
                break;  
         case "1":
            console.log("one dog");
            break;
         default:
            console.log("too many dogs!");
            break;
          }
    12. 声明一个Object:  
        var myObj = {  
            name: "ltcinos",  
            age:  28,  
            gender: "male",  
        }  
    13. **There are two ways to create an object:** using **object literal notation** (which is what you just did) and using the **object constructor**.

Literal notation is just creating an object with curly braces, like this:
  1. var myObj = {
  2. type: ‘fancy’, //注意是 : 而不是 =, 但是vav = new Object(); 之后的赋值就要用=
  3. disposition: ‘sunny’
  4. };
  5. var emptyObj = {};
When you use the constructor, the syntax looks like this:

var myObj = new Object();

This tells JavaScript: "I want you to make me a `new` thing, and I want that thing to be an `Object`.

You can add keys to your object after you've created it in two ways:
  1. myObj[“name”] = “Charlie”;
  2. myObj.name = “Charlie”;
Both are correct, and the second is shorthand for the first.

    14. 嵌套Object: you can creat object with object:  
   var friends = new Object();  
   friends.bill={  
       name : "Bill"  
       }  
   friends.steve={  
       name : "Steve"  
       }  
    15. for/in loop -- 不太理解。

      var list = function(obj){
          for (var id in obj){
          console.log(id);
          }
      };

      list(myObject);

    16. 这里我要贴一个JavaScript的程序段了:关于对象的声明和调用,for in用法,就是按id找同一class下的所有对象。参考下面第26点。
  1. var friends = new Object();
  2. friends.bill = {
  3. firstName:“Bill”,
  4. lastName:“Gates”,
  5. number:“88888888”,
  6. address: “8888 BillGates’ house”,
  7. };
  8. friends.steve = {
  9. firstName:“Steve”,
  10. lastName:“Jobs”,
  11. number:“0000000”,
  12. address: “000 S Jobs’ house.”,
  13. };
  14. var list = function(Obj){
  15. for (var xx in Obj){
  16. console.log(“xx: " + xx);
  17. }
  18. };
  19. var search = function(name){
  20. for(var id in friends){
  21. if (name === friends[id].firstName){ //can’t use friends.id.firstname
  22. console.log(friends[id]);
  23. return friends[id];
  24. }
  25. }
  26. }
  27. list(friends);
  28. search(“Steve”);
  
  
   17.  关于Object中的Property的access:
  1. // Take a look at our next example object, a dog
  2. var dog = {
  3. species: “greyhound”,
  4. weight: 60,
  5. age: 4
  6. };
  7. var species = dog[“species”];
  8. // fill in the code to save the weight and age using bracket notation
  9. var weight = dog.weight;
  10. var age = dog[“age”];
  
**we accessed properties using what is known as dot notation.** Good name, right? So to access a property, we use `ObjectName.PropertyName` (e.g., `bob.name`)

**In addition to dot notation, we can also access properties using bracket notation.**  In this case we use `ObjectName["PropertyName"]` to access the desired property. Note, we need `" "` around the property's name.

  
  18.  关于Object, Method声明与使用:
  1. // bob has age of 17
  2. var bob = {
  3. age : 17, //[注意]此处不能写成bob.age:17
  4. }
  5. // this time we have added a method, setAge
  6. bob.setAge = function(age){ //注意不能写成 var bob.setAge,
  7. bob.age = age; //如果是this.age = age;上面就要用var,并指派bob.setage = setage;注意没有()
  8. }
  9. // add a method, getYearOfBirth
  10. bob.getYearOfBirth = function(age){
  11. return 2014-age;
  12. }
  13. //console.log via the getYearOfBirth
  14. console.log(bob.getYearOfBirth(14));
  
    19. this 的2种用法:  
1. this在通用method中,作为通用object替代位置:  
-----e.g.Code-----  
  var susan = new Object();  
  susan.height = 8;  // 【CAUTION】not :  
  var setHeight = function(height){  
    this.height = height;  
  }  
  susan.setHeight = setHeight; //attribute the mothod to Object!  
  susan.setHeight(9);  // call the method.  
----------  
2. this在特定method中,作为位置替代:  
------e.g.Code-----  
  var susan = {  
    height : 8,  
  }  
  susan.setHeight = function(newHeight){  
    this.height = newHeight;	//this replace the "susan".height  
  }  
  susan.setHeight(9);  
  console.log(susan.height);  
-------------------  
    **20. Constructor的用法,建立所谓的类class及它的methods**  
  1. //看看Constructor是怎么玩的:
  2. function Cat(age, color) {
  3. this.age = age;
  4. this.color = color;
  5. }
  6. var Tom = new Cat(18,“gray”) //别忘了var,new
  7. console.log(Tom.age);
  8. //下面是函数的语法
  9. var myFuc = function (a,b){
  10. var c = a+b;
  11. }
  
    **21. Constructor with methods:**
  1. function Rectangle(height, width) {
  2. this.height = height;
  3. this.width = width;
  4. // put our calcArea function here!
  5. this.calcArea = function() {
  6. return this.height * this.width;
  7. };
  8. // put our calcPerimeter function here!
  9. this.calcPerimeter = function(){
  10. return (this.height + this.width)*2;
  11. };
  12. }
  13. var rex = new Rectangle(13,4); //creat Rectagle, name:rex
  14. var area= rex.calcArea();//calc area for rex with calcArea不要忘了()
  15. var perimeter=rex.calcPerimeter();//calc perimeter for rex with calcP..
  
    22.**关于Constructor要注意的重点位置:**
 
 * 以function开始:function ConstructorName(para1,para2){}
* 以this替代类名:this.height = para1; 分号结尾。this.width = para2;
* 与Array合用,Array的声明: var myArray = [];

    23.其实Object的属性properties有两种引用方法:
Properties are like variables that belong to an object, and are used to hold pieces of information. Properties can be accessed in two ways:


 
 * Dot notation, with `ObjectName.PropertyName`
* Bracket notation, with`ObjectName["PropertyName"]` (don't forget the quotes!)

    24. 在函数中新建一个Object:
  
  1. //假设table是一个object的数组,每个object内包含width, height,
  2. //现在要增加一个object,即在table[table的长度]上增加一个obj
  3. var add = function(width,height){
  4. table[table.length] = { //这是在原数组 table[] 基础上新增一个元素
  5. width : width,
  6. height : height,
  7. };
  8. };
  
    25.使用Constructor建立class时,内部声明method方法:    ![](https://img-blog.csdn.net/20150205170842027?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc29uaWN0bA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)    25. 类型检查工具typeof myObj与property查询工具:myObj.hasOwnProperty('propName')    26. 关于全面查询properties of an Object: 这里要呼应一下前面第16点,介绍的for in loop:    示例代码如下:    
  1. var nyc = {
  2. fullName: “New York City”,
  3. mayor: “Bill de Blasio”,
  4. population: 8000000,
  5. boroughs: 5
  6. };
  7. //打印所有properties of nyc
  8. for(var prop in nyc){
  9. console.log(prop);
  10. }
  
    27.     **Javascript学习笔记1自测复习:**
  1. javascript自测复习:
    1.  	提取substring
      
    1.  	//ask user to confirm
      
    1.  	//ask user to type in
      
    1.  	//Print out the content: 					console.log();
      
    1.  	//declare a variable:						var myVariable;
      
    1.  	//declare a function:						var myFk = function(inPut){};
      
    1.  	//declare an empty array:					var myArr= [];
      
    1.  	//how to use switch:						switch(myIn){case "0": xxx; break;}
      
    1.  	//declare an Object:					var myObj = { name : "so", xx:yy, qq:ww,};
      
    1. 	//two ways to create an object:				var myObj = new Object(); //constructor
      
    1. 	//add keys to object:					myObj["name"] = "";  myObj.name = "";
      
    1. 	//嵌套object:		var friends = new Object();	friends.bill = {name: "bill"}
      
    1. 	//for/in loop, access 嵌套objcet's properties		for(var x in friends){ friends[x].firstname = "Bill";} //name all as "Bill"
      
    1. 	//access the properties in an obj			two ways:1. var age = dog.age;  2.var age = dog["age"];
      
    1. 	//Declare Obj, Method but function			bob.setage = function(age){ bob.age = age;}
      
    1. 	//two ways of using "this"
      
  2. var setAge = function(age){ this.age = age; }
  3. susan.setAge = setAge;
  4. susan.setAge(19);
  5. //2nd way:
  6. susan.setHeight = function(height){ this.height = height ; //or “susan.height = height;”
  7. }
    1. 	//creat class and method via Constructor
      
  8. //create class:
  9. function Cat(age, colour){ this.age = age; this.colour = colour;}
  10. //conclude the key word “function”:
  11. //a) create a function:
  12. var myFk = function(a,b){ var c = a+b;}
  13. //b) create a public method, and attribute to an Obj:
  14. var setAge = function(age){ this.age = age;}
  15. susan.setAge = setAge;
  16. //c) Constructor for create a new class:
  17. function Cat(age, color){ this.age = age; this.color = color;}
  18. var Tom = new Cat(3, “gray”);
  19. //d) Constructor for method:
  20. //when we creat a new class, we use in the Class, by below:
  21. this.myMethod = function(){ return 2014-this.age; }
    1. 	//Constructor for method:"this.myMethod = function(){this.prop}"
      
  22. //1. create the class
  23. //2. contain the method into the creation of class
  24. function Rectangle(width, length){
  25. this.width = width;
  26. this.length = length;
  27. //methods begins here:
  28. this.calcArea = function(){
  29. return this.length*this.width;
  30. }
  31. this.calcPerimeter = function(){
  32. return (this.length+this.width)*2;
  33. }
  34. }
  35. //use it:
  36. var rex = new Rectangle(13,5); //create Obj via Class
  37. var area= rex.calcArea();
  38. var peri= rex.calcPerimeter();
    1. 	//type check:"typeof myObj"
      
    1. 	//呼应第16点中的 for/in loop
      
  39. var nyc = {
  40. name: “New York City” ,
  41. age: 300,
  42. address: “The East of USA”
  43. }
  44. for (var prop in nyc){
  45. console.log(prop);
  46. }
  
Published At
comments powered by Disqus