const myHeroes = ['蝙蝠俠','蜘蛛人','水行俠','黑寡婦'];
console.log(myHeroes.indexOf('蟻人'));
"沒有找到為-1" -1
console.log(myHeroes.indexOf('水行俠'));
//
//"索引2就是水行俠:" ,2
js 三元運算子
const age =20; const result =( age>=18 ) ? true:false; console.log( result ) // true
Promise.all
Promise.all
function promeseA (){
return new Premise((resole,reject)=>{
setTimeout(()=>{
console.log('A')
resole('A')
},1000)
})
}
function promeseB (){
return new Premise((resole,reject)=>{
setTimeout(()=>{
resole('B')
},3000)
})
}
Promise.all().then(resole=>{
console.log('Promise.all',resole);
})
最终返回的结果
//“[object Array] (2) [“A”,”B”]
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