我正在努力理解创建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
})();
点击此处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();