常用的JavaScript代码片段

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值