const juice = `Juice with ${applePieces} pieces of apple and ${orangePieces} pieces of orange.`; return juice; }
alert(fruitProcessor(2, 3));
3-7 Reviewing Functions
已整合进上文
3-8 Coding Challenge #1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
constcalcAverage = (a, b, c) => (a + b + c) / 3; let avgDolphins = calcAverage(85, 54, 41);//use let, so we can reassign them. let avgKoalas = calcAverage(23, 34, 27);//use let, so we can reassign them. console.log(avgDolphins, avgKoalas);
const checkWinner = function (avgDolphins, avgKoalas) { if (avgDolphins >= avgKoalas * 2) { console.log(`Dolphins win (${avgDolphins} vs. ${avgKoalas})`); } elseif (avgKoalas >= avgDolphins * 2) { console.log(`Koalas win (${avgKoalas} vs. ${avgDolphins})`); } else { console.log(`No team wins!`); } }; checkWinner(2, 1);
//返回String const interestIn prompt('What do you want to know about Jonas? Choose between...'); console.log(jonas.interestedIn); //错!jonas没有“interestedIn”属性(返回undefined) console.log(jonas[interestedIn]);
//Jonas has 3 friends, and his best friend is called Micheal. console.log(`${jonas.firstName} has ${jonas.friends.length} friends, and his best friend is called ${jonas.friends[0]}.`);
for (let i = 0; i < years.length; i++) { ages.push(2037 - years[i]); } console.log(ages);
continue会跳过当前的迭代;break会完全终止整个循环。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// continue and break //continue:输出所有字符串 console.log('--- ONLY STRINGS ---') for (let i = 0; i < jonas.length; i++) { if (typeof jonas[i] !== 'string') continue;
console.log(jonas[i], typeof jonas[i]); }
//break:只输出第一个数字 console.log('--- BREAK WITH NUMBER ---') for (let i = 0; i < jonas.length; i++) { if (typeof jonas[i] === 'number') break;
for (let i = arrayList.length - 1; i >= 0; i--) { console.log(i, arrayList[i]); }
3-19 The while Loop
while用于不确定次数的循环,比如掷骰子。 用for掷出1000次骰子:(bushi
1 2 3 4 5 6 7 8 9 10 11 12
let dice; for (let i = 0; i < 1000; i++) { dice = Math.trunc(Math.random() * 6) + 1; if (dice != 6) { console.log(`You rolled a ${dice}`); alert(`You rolled a ${dice}`); } else { console.log(`You got ${dice} within ${i + 1} roll(s)!`); alert(`Congratulation! You got ${dice} within ${i + 1} roll(s)!`) break; } }
不对不对,我们这节学while。
1 2 3 4 5 6 7
let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 6) { console.log(`You rolled a ${dice}`); dice = Math.trunc(Math.random() * 6) + 1; if (dice === 6) console.log('Loop is about to end...'); }
总之,学了两个Math方法,**Math.random()产生一个0.几的浮点数,Math.trunc()**向下取整。 Move on to the next episode.