/** 條件:三個空酒瓶還一瓶酒,5個瓶蓋換一瓶酒,酒 5 元一瓶,共100元 */functionbuyWine({ x =20, y =20, n =20}={}){if(x -3<0&& y -5<0){
console.log("------親,您一共可以買"+ n +"瓶酒哦--------");}else{var _x = x,
_y = y;
n = n +(x -(x %3))/3+(y -(y %5))/5;
y =(_x -(_x %3))/3+(y -(y %5))/5+(y %5);
x =(_y -(_y %5))/5+(x -(x %3))/3+(x %3);
console.log("每一次兌換後,空酒瓶個數:"+ x,"瓶蓋個數:"+ y,"總數爲:"+ n);
arguments.callee({ x, y, n })// buyWine({ x, y, n })}}functioninit(totalMoney){let x =(totalMoney - totalMoney %5)/5,
y =(totalMoney - totalMoney %5)/5,
n =(totalMoney - totalMoney %5)/5;return{ x, y, n };}buyWine(init(100));
數組排序
// 冒泡排序
bubbleSort: arr =>{for(var i =0, len = arr.length; i < len; i++){for(var j = i +1; j < arr.length; j++){if(arr[i]< arr[j]){[arr[j], arr[i]]=[arr[i], arr[j]];}}}return arr;},// 插入排序
insertSort: arr =>{var temp;// temp變量用於臨時存儲待插入元素for(var i =1; i < arr.length; i++){// 外層循環相當於選擇插入的位置
temp = arr[i];//從前往後查找插入位置for(var j = i; j >0&& arr[j -1]> temp; j--){// 內層循環和插入當前位置之前的元素進行比較
arr[j]= arr[j -1];//將大於temp的arr[j]元素後移}
arr[j]= temp;}return arr;},// 選擇排序
selectSortS: arr =>{var minIndex;//定義minIndex變量用於存儲每一趟比較時的最小數的下標for(var i =0; i < arr.length; i++){// 外層循環改變當前默認元素的下表
minIndex = i;for(var j = i +1; j < arr.length; j++){// 內層循環找當前最小元素的小標if(arr[minIndex]> arr[j]){
minIndex = j;}}//每輪比較後若arr[i]不是我們需要的最小那個數,則進行交換if(minIndex !== i){[arr[i], arr[minIndex]]=[arr[minIndex], arr[i]];}}return arr;},// 快速排序
quickSort: arr =>{if(arr.length <=1){// 如果數組只有一個數,就直接返回;return arr;}var num = Math.floor(arr.length /2);//找到中間數的索引值,如果是浮點數,則向下取整var newValue = arr.splice(num,1);//找到中間數的值var left =[],
right =[];for(var i =0; i < arr.length; i++){if(arr[i]< newValue){
left.push(arr[i]);//基準點的左邊的數傳到左邊數組}else{
right.push(arr[i]);//基準點的右邊的數傳到右邊數組}}returnquickSort(left).concat(newValue,quickSort(right));//遞歸不斷重複比較},
數組去重複
// 自定義添加方法去重複方法 可以是各種類型// var arr3= [0, 1, '1', true, 5, true, false, undefined, undefined, null, null];
unique: arr =>{var hash ={},
result =[],
type ="",
item;for(var i =0; i <this.length; i++){
item =this[i];
type = Object.prototype.toString.call(item);// 專門用來判斷字符串的類型的if(!hash[item + type]){
hash[item + type]=true;
result.push(item);}}return result;}// console.log(arr3.unique());};
數組扁平化處理
flattenOne: arr =>{var res =[];for(var i =0; i < arr.length; i++){if(Array.isArray(arr[i])){
res = res.concat(flattenOne(arr[i]));}else{
res.push(arr[i]);}}return res;},// reduce
flattenTwo: arr =>{return arr.reduce(function(prev, item){return prev.concat(Array.isArray(item)?flattenTwo(item): item);},[]);},// 擴展運算符
flattenThree: arr =>{while(arr.some(item => Array.isArray(item))){
arr =[].concat(...arr);}return arr;},