Assignment 2 (pdf)

Make sure to test all your answers in the console.

  1. In this question we will be working with arrays. Start a new console and define an array via: var a = [Math.random(), Math.random(), Math.random()].
    1. Write an expression that would return the middle element of the array (for this particular array, that has length 3, not in general).
    2. Write an expression that would return a new array containing the last two elements from a. You should use slice to do it.
    3. Define an array via var b = ["hi", "there", "you"]. Which of the following would result in the string "hi,there,you"? Circle all that are correct.
      1. b.join().
      2. b.join(,).
      3. b.join(",").
      4. b.join(',').
      5. b.join("hi,there,you").
    4. The following code is supposed to compute the sum of the squares of the numbers in the array. Fill in the right hand side of the assignment:
    var s = 0, i;
    for (i = 0; i < a.length; i += 1) {
    
        s =  ...                              // Fill this in
    
    }
    console.log(s);
  2. This question concerns the object var o = { foo: 23, bar: 5 }.
    1. Which of the following would return 23? circle all that are correct.
      1. o.foo
      2. o[foo]
      3. o[("foo")]
      4. o."foo"
    2. What would o.baz return?
      1. nothing
      2. undefined
      3. null
      4. 5
      5. It will produce an error.
    3. After the line o.bar = undefined, how many keys does o have?
      1. 1
      2. 2
      3. 3
    4. After the line o.bar = { baz: 2 }, what would o["bar.baz"] return?
      1. 2
      2. undefined
      3. null
      4. It will produce an error
  3. For this question we start with an array of objects from a shopping cart:

    var cart = [
        { item: "shirt", quantity: 1 , price: 10 },
        { item: "shoes", quantity: 3 , price: 5 },
        { item: "pens" , quantity: 10, price: 2 }
    ];
    1. The following code is meant to compute the total cost of everything in the cart. The prices are per item, so they need to be multiplied by the quantities. Fill in the body of the loop:

      var total = 0, i, obj;
      for (i = 0; i < cart.length; i += 1) {
      
                                              // Fill this in
      
      }
      console.log(total);
    2. We decide that we want to buy two more shoes, so we want to change the information in the cart to have the adjusted quantities. Write an expression that would make that happen.