用闭包实现一个数据累加并添加进数组中
#需求现在是这样哈,传过来一个值,然后从1到这个值输出第几层这样的东西组成一个数组.,需求很简单哈,就是突然心血来潮想用闭包来简单实现一下.
先看原生:
function num(buildNum){ //传入的值
var buildArr = []; //保存的数组
var buildStr = ''; //输出的字符串
for( var i =1;i<=buildNum;i++ ){
buildStr = `第 ${i} 层`
buildArr.push(buildStr)
}
console.log(buildArr)
}
num(5) //没有规定假如没传参,默认多少层
接下来是用闭包实现哈:
function buildSum(){
var buildNum = arguments[0] || 10; //如果没传入参数,默认为10
var buildStr = '';
function buildAdd(){
var buildArr = []
for(var i =1;i<=buildNum;i++){
buildStr = `第 ${i} 层`;
buildArr.push(buildStr)
}
console.log(buildArr)
}
return buildAdd
}
var numAdd = buildSum();
numAdd()