发布新日志

  • Objects in JavaScript

    2012-03-07 15:34:49

    1. 2 ways to create Object in JavaScript.:
    1. Literal notation is the one where we declare the object, and, at the same time, define properties and values in the object. It makes use of { }. See first one for an example.

    2. Constructor notation is where we make use of the keywords new Object(). We then use dot notation to add property and values to the object. See second one for an example.

    //Literal
    var australia = {   
    weather: "superb",   
    people: "not many of them but they're all great!",
    tourism: "a wonderful place to holiday. please visit!"};

    //Constructor
    var jordan = new Object();
    jordan.weather = "hot. but so are the people!";
    jordan.people = "see above!";
    jordan.tourism = "Codecademy's dream team retreat!";


    2. There are two different ways that we can retrieve an object's properties: dot and bracket notation.

    1. Dot notation: obj.myProp
    2. Bracket notation: obj["myProp"]   (You can also use variable in bracket notation.

    3. Functions in object are called Method.

    4. this keyword: Why is using the this keyword helpful? Imagine we have a method that has a lot of complicated code and references an object's properties. We also want many objects to have this method. We can create a single generic method that uses the this keyword. Now many objects can use this method by defining a method that simply equals this generic method.

  • 使用Math.floor和Math.random取随机整数

    2012-03-07 15:11:38

    Math.random():获取0~1随机数

    Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (小于等于 x,且与 x 最接近的整数。)
    其实返回值就是该数的整数位:
    Math.floor(0.666)   -->  0
    Math.floor(39.2783)   -->  39

    所以我们可以使用Math.floor(Math.random())去获取你想要的一个范围内的整数。
    如:现在要从1~52内取一个随机数:
    首先Math.random()*52  //这样我们就能得到一个 >=0 且 <52的数
    然后加1:Math.random()*52 + 1    //现在这个数就 >=1 且 <53
    再使用Math.floor取整

    最终: Math.floor(Math.random()*52 + 1)
    这就能得到一个取值范围为1~52的随机整数了.
Open Toolbar