var str = 'My name is ${name}. I like ${hobby}.'; var obj = { name: 'Tom', hobby: 'coding' }; // 結果應爲 'My name is Tom. I like coding.'
const arr = [ { id: 1, priority: 16 }, { id: 2, priority: 20}, { id: 3, priority: 3 }, { id: 4, priority: 7 } ];
3.a、b、c 都是執⾏異步操做的函數,請經過 Promise、async、await 實現:a、b 並⾏執⾏完畢後再執⾏ c。面試
function a(callback) { setTimeout(callback, 10); } function b(callback) { setTimeout(callback, 20); } function c(callback) { setTimeout(callback, 30); }
<style> .box{ width:100vw; height:100vh; display: flex; } .left{ width: 200px; } .right{ flex: 1; } </style>
<div class="box"> <div class="left"></div> <div class="right"></div> </div>
<style> .box{ width: 200px; height: 200px; position: fixed; left: 50%; top: 50%; transform: translate3d(-50%,-50%,0); z-index: 99; } </style> <div class="box"></div>
使⽤正則表達式把字符串 str 中的佔位符替換成 obj 的對應屬性值,要求只能調⽤⼀次 replace ⽅法。正則表達式
var str = 'My name is ${name}. I like ${hobby}.'; var obj = { name: 'Tom', hobby: 'coding' }; // 結果應爲 'My name is Tom. I like coding.' var newStr = str.replace(/\$\{(.+?)\}/g,(str, k) => { return obj[k] }) console.log('newStr = ',newStr)
從數組中隨機選出⼀個元素,要求:priority 越⼤的元素,被選中的機率越⼤。數組
const arr = [ { id: 1, priority: 16 }, { id: 2, priority: 20}, { id: 3, priority: 3 }, { id: 4, priority: 7 } ]; function randomNum(Min, Max) { var Range = Max - Min var Rand = Math.random() var num = Min + Math.round(Rand * Range) return num } const countVal = arr.reduce((count, item) => count += item.priority, 0) arr.map(item => { item.probability = parseInt(item.priority / countVal * 100) item.text = `當前item中獎的機率爲 ${item.probability} %` for (let i = 0; i <= 100; i++) { if (item.probability >= i) { const num = randomNum(0, 100) if (num === 100) { item.checked = true return } } } }) console.log(arr) 或者 var arr=[ {id:1,p:16}, {id:2,p:20}, {id:3,p:3}, {id:4,p:7} ]; var sum =arr.reduce(function(t,v){ return v.m=t+=v.p; },0); var rd = randomNum(0,sum); var item=arr.find(function(v){ return rd<v.m; }); console.info('隨機數:'+rd); console.info('隨機元素:'+JSON.stringify(item)); console.info('當前元素機率爲:'+(item.p/sum));
a、b、c 都是執⾏異步操做的函數,請經過 Promise、async、await 實現:a、b 並⾏執⾏完畢後再執⾏ c。promise
function a(callback) { setTimeout(callback, 10); } function b(callback) { setTimeout(callback, 20); } function c(callback) { setTimeout(callback, 30); } promiseHandler() async function promiseHandler() { function a(callback) { setTimeout(callback, 3000); } function b(callback) { setTimeout(callback, 20); } function c(callback) { setTimeout(callback, 100); } const p1 = function() { return new Promise(resolve => { a(() => resolve('a') ) }) } const p2 = function() { return new Promise(resolve => { b(() => resolve('b') ) }) } const p3 = function() { return new Promise(resolve => { c(() => resolve('c') ) }) } const arr = await Promise.all([p1(), p2()]) console.log(arr[0]) console.log(arr[1]) console.log(await p3()) }