1.使用isNaN(),parseFloat()和isFinite()检查参数是否为数字。
function isNumber(number){
return !isNaN(parseFloat(number)) && isFinite(number);
}
isNumber(5); //returns true
isNumber("Hello"); //returns false
2.使用reverse(),split(),join()反转字符串。
let str = "Hello World";
str.split("").reverse().join(""); //returns 'dlroW olleH'
3.使用Math.random()和Math.floor()取数组中的随机项。
et cars = ['Ford', 'Ferrari', 'BMW', 'Toyota'];
//Store a random array item in a variable.
let randomCar = cars[Math.floor(Math.random()* cars.length)];
//Print the random item from car array.
console.log(randomCar); //returns random element
4.二进制转十进制,再使用String.fromCharCode()将小数转为文本。
function binaryToText(binary) {
//Convert binary into an array of strings separated by whitespace. binary = binary.split(' ');
//convert from binary to decimals to text.
return binary.map(elem => String.fromCharCode(parseInt(elem, 2))).join("");
}
binaryToText("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01001010 01100001 01110110 01100001 01010011 01100011 01110010 01101001 01110000 01110100"); //returns I love JavaScript
binaryToText("01010100 01101000 01100001 01110100 00100111 01110011 00100000 01100111 01101111 01101111 01100100"); //returns That's good
5.使用Math.max()和Math.min()获取数据中的最大和最小数字。
let nums = [67, 99, 4, 2, 77];
//minimum number
Math.min(...nums); //returns 2
//maximum number
Math.max(...nums); //returns 99
6.使用performance.now()方法检查代码执行时长。
var start = performance.now();
//Your piece of code starts here
for(let i = 0; i < 100; i++){
console.log(i);
}
//Your piece of code ends here
var duration = performance.now() - start;
console.log(duration); //54.89999961853027
7.利用三元运算符的箭头函数计算一个数的阶乘。
const getFactorial = num =>
num < 0 ?
(()=>{
throw new TypeError('No negative numbers');
})()
: num <= 1
? 1
: num * getFactorial(num - 1);
//examples:
getFactorial(0); //returns 1
getFactorial(5); //returns 120