Definitive Guide练习

 1. 把对象作为参数传入function

var a = [1,2,3,4];

var b = [];





function arraycopy(/* array */ from, /* index */ from_start,

/* array */ to, /* index */ to_start,

/* integer */ length) {

  var j = to_start - 1;

  for(var i = from_start - 1; i < length; i++) {

    to[j] = from[i];

    j += 1;

  }

}





function copyArray(arrObj){

  arraycopy(arrObj.from,

            arrObj.from_start || 0,

            arrObj.to,

            arrObj.to_start || 0,

            arrObj.length) 

}





/*

console.log("Array a is: " + a);

console.log("Initial Array b is: " + b);



arraycopy(a, 1, b, 1, 4);



console.log("New Array is: " + b);

*/



console.log("Initial Array b is: " + b);





var o = {

  from : a,

  to : b,

  length : 4

};



copyArray(o);



console.log("New Array is: " + b);

2. try/catch/finally

function factorial(x) {

  if(x === undefined || x < 0) {

    throw new Error("x is incorrect, please put a positive value");

  }

  for (var i = 1; x > 1; x--) {

    i *= x;

  }

  return i;

}







try{

  var n = Number(prompt("Please enter a number", ""));

  var f = factorial(n);

  console.log(f);

}

catch(err) {

  alert(err);

}

 

 

你可能感兴趣的:(init)