forEach()

forEach():迴圈的陣列

forEach()本身可帶兩個參數:第一個是必須的 callback 函式,第二個參數thisArg 是可選擇性的。這個callback 函式會將 Array 中的每一個元素作為參數,帶進這個 callback 函式裡,每個元素各執行一次。

第一個 callback 函式則可傳入三個參數:
currentValue 目前被處理的陣列元素值
index 目前被處理的陣列元素索引(可選)
array 呼叫forEach()陣列本身(可選)

const newArr = arr.forEach(function (currentValue, index, array){
  //...
});

使用箭頭函示的縮寫

const fruits = ["apple", "orange", "cherry"];
fruits.forEach((item, i)=> {
  console.log(i, item)
  //0 "apple"
  //1 "orange"
  //2 "cherry"
});

map():處理陣列

map()

透過函式產生一個新陣列

不會改變原陣列

回傳等於原陣列

如不回傳是undefined

語法

const newArr = arr.map(function (value, index, array){
  return  ...
});

回調函式(callback)與三個參數:value,index,arr

const shoppingCart = [
  {itemName: "Book",price : 220 },
  {itemName: "Bag",price : 350 }
];
// 使用箭頭函示的縮寫
const itemNames = shoppingCart.map(x => 
  x.itemName
); 
console.log(itemNames )
// 只把 itemNames 提取出來
itemNames; // ["Book", "Bag"]

// 把 price 打七九折後提取出來
const discounts = shoppingCart.map(x => x.price * 0.79); 
discounts; 
console.log('折扣:discounts',discounts)
// [173.8, 276.5]



//小於 50標示無折扣
const prices = [42, 57, 89, 23, 78, 12]
const newPrices = prices.map( function(elem) {
  if(elem < 50) return "無折扣";
return elem
});

newPrices; 
console.log(newPrices)
//["無折扣",57,89,"無折扣",78,"無折扣"]

價格大於999元,均8折

map() & Math.max 取出最大值

Math.charAt()

charAt():從一個字符串中返回指定的字符

const anyString = "Brave new world";
console.log(anyString.charAt(0))//"B"
console.log(anyString.charAt(1))//"r"
console.log(anyString.charAt(3))//"v"
console.log(anyString.charAt(4))//"e"
console.log(anyString.charAt(5))//"n"
console.log(anyString.charAt(6))//" "
console.log(anyString.charAt(999))//" "

Math.atan2():靜態方法返回平面中正 x 軸與從 (0, 0) 到點 (x, y) 的射線之間的角度(以弧度為單位)

Math.atan2():靜態方法返回平面中正 x 軸與從 (0, 0) 到點 (x, y) 的射線之間的角度(以弧度為單位)

function calcAngleDegrees(x, y) {
  return Math.atan2(y, x) * 180 / Math.PI;
}

console.log(calcAngleDegrees(5, 5));
// Expected output: 45

console.log(calcAngleDegrees(10, 10));
// Expected output: 45

console.log(calcAngleDegrees(0, 10));
// Expected output: 90

Math.max():查詢最大值

Math.max():查詢最大值

var myArray1 = [1, 5, 6, 2, 3];
var max1 = Math.max(...myArray1);
console.log('max1',max1)
//"max1" 6

function MyMax(myarr){
    var al = myarr.length;
    maximum = myarr[al-1];
    while (al--){
        if(myarr[al] > maximum){
            maximum = myarr[al]
        }
    }
    return maximum;
};

var myArray2 = [1, 5, 8, 2, 3];
var max2 = MyMax(myArray2);
console.log('max2',max2)
//"max2" 8

Math.tan():返回以弧度為單位的數字的正切值

Math.tan():返回以弧度為單位的數字的正切值

function getTanFromDegrees(degrees) {
  return Math.tan(degrees * Math.PI / 180);
}

console.log(getTanFromDegrees(0));
// Expected output: 0

console.log(getTanFromDegrees(45));
// Expected output: 0.9999999999999999

console.log(getTanFromDegrees(90));
// Expected output: 16331239353195370