-1

我试图了解创建 OO js 函数的过程,我想以 Euler #1 作为示例http://projecteuler.net/problem=1。我追求的是可读性而不是优雅。我的尝试如下,我已经在http://jsfiddle.net/mcgraw73/wGFNK/上设置了小提琴

(function euler1() {
//array for holding all numbers 1 thru 1000
var numArr = [];

//array for holding multiples of 3 and 5 < 1000
var divArr = [];

//fill numArr[]
function createArrayNums() {
    for (var i = 1; i <= 999; i++) {
        numArr[i] = i;
        //console.log(i);
    }
}

//go thru numArr, if any of the elements divided by 3 || 5 === 0 push those values into     divArr[]
function createDivArray() {
    var k;
    for (var i = 0; i <= numArr.length; i++) {
        if (numArr[i] % 3 === 0 || numArr[i] % 5 === 0) {
            k = i;
            divArr.push(k);
            //console.log(k);
        }
    }
}

//run the functions that fill array's
createArrayNums();
createDivArray();

//get the sum of the elements in divArr[]
var sumOfMultiples = 0;
for (var i in divArr) {
    sumOfMultiples += divArr[i];
}

//give me the answer
alert("the sum of the multiples of 3 && 5 < 1000 = " + sumOfMultiples);

//alert----> the sum of the multiples of 3 && 5 < 1000 = 233168

})();
4

1 回答 1

2

Fiddle 这里http://jsfiddle.net/XJepE/ 基本结构

var MyObject=( function(){
     var my_private vars;
     function private_function(){
     }
     return {
          public_method: function(){
          },
          another_public_method: function(){
          }
     };

})();
// call a method
myObject.public_method();
于 2013-07-03T18:38:28.267 回答