# 每天学习 10 个实用Javascript代码片段（六）

+关注继续查看

### 1. Randoms

const getRandoms = (min, max) => {
return Math.round(Math.random() * (max - min) + min);
};
console.log(getRandoms(10, 100));

const arrayCities = ["北京", "上海", "广州", "深圳", "天津", "重庆"];
array[Math.floor(Math.random() * array.length)];
console.log("随机城市：", getRadmonItem(arrayCities));

### 2. 数字加密

function Encrypt(secretNumber) {
const _secretNumber = secretNumber;
const encrypted = (encryptNumber) => encryptNumber ^ _secretNumber;
const decrypted = (encryptedContent) => encryptedContent ^ _secretNumber;
return {
encrypted,
decrypted,
};
}
const encryptHelper = new Encrypt(202108);
const encryptNumber = 20210901;
// 加密
const encrypted = encryptHelper.encrypted(encryptNumber);
console.log(encrypted); // 20410793
// 解密
const decrypted = encryptHelper.decrypted(encrypted);
console.log(decrypted); // 20210901

### 3. 设置必选参数

const mandatory = (name) => {
throw new Error(调用错误，必须传递参数：${name}); }; const printTitle = (title = mandatory("标题")) => { console.log(打印文章标题：${title});
};
printTitle("JavaScript"); // 打印文章标题：JavaScript
printTitle(); // Error: 调用错误，必须传递参数：标题

### 4. 动态创建函数

const multiplyFn = new Function(
"num1",
"num2",
"num3",
"return num1*num2*num3"
);
console.log(multiplyFn(1, 2, 3)); // 6
// ES6
const multiply = new Function(
"...numbers",
"return numbers.reduce((acc,current) => acc * current, 1)"
);
console.log(multiply(1, 2, 3)); // 6

### 5. 清空数组

const arrayCities = ["北京", "上海", "广州", "深圳", "天津", "重庆"];
console.log(arrayCities); // [ '北京', '上海', '广州', '深圳', '天津', '重庆' ]
// 清空
arrayCities.length = 0;
console.log(arrayCities); // []

### 6. 四舍五入

const pi = 3.14159265359;
console.log(pi.toFixed(3)); // 3.142
const sumFloat = 0.1 + 0.2;
console.log(sumFloat); // 0.30000000000000004
console.log(sumFloat.toFixed(1)); // 0.3

Math 方法中常见用于取整的包括：Math.round() 舍入到最接近的整数， Math.floor() 向下舍入， Math.ceil() 向上舍入。最接近数学意义上四舍五入的方法就只有 toFixed ，如下代码片段所示：

const pi = 3.14159265359;
console.log(pi.toFixed(0)); // 3
console.log(Math.floor(pi)); // 3
console.log(Math.ceil(pi)); // 4
console.log(Math.round(pi)); // 3
const num2 = 3.5;
console.log(num2.toFixed(0)); // 4
console.log(Math.floor(num2)); // 3
console.log(Math.ceil(num2)); // 4
console.log(Math.round(num2)); // 4

### 7. 数组项的对象解构

const csvAddressDetail = "广东省,深圳市,南山区,科技园北区科技园大厦";
const { 0: province, 1: city, 2: district, 3: address } = arrayAddress;
console.log(province, city, district, address);  // 广东省 深圳市 南山区 科技园北区科技园大厦

const arrayAddress = csvAddressDetail.split(",");
console.log(city, address); // 深圳市 科技园北区科技园大厦

### 8. 变量数字转换

console.log(+"15"); // 15
console.log(+true); // 1
console.log(+false); // 0
console.log(+null); // 0
console.log(Number("15")); // 15
console.log(parseInt("15", 10)); // 15
console.log(parseFloat("15.42")); // 15.42

### 9. 获取文件扩展名

const arrayFiles = [
"/attach/pics/logo.png",
"logo.svg",
"template.xlsx",
"template.doc",
];
const getExtName = (fullpath) => {
const root = fullpath.split(/[\\/]/).pop();
const pos = root.lastIndexOf(".");
return root === "" || pos < 1 ? "" : root.slice(pos + 1);
};
const arrayExtNames = arrayFiles.map((item) => getExtName(item));
console.log(arrayExtNames); // [ 'png', 'svg', 'xlsx', 'doc' ]

### 10. 普通函数定义

const calculator = (operation, ...numbers) => {
return operation(...numbers);
};
return numbers.reduce((acc, num) => acc + num, 0);
}
function subtract(...numbers) {
return numbers.reduce((acc, num) => acc - num, 0);
}
function multiply(...numbers) {
return numbers.reduce((acc, num) => acc * num, 1);
}
console.log(calculator(add, 1, 2, 3, 4, 5)); // 15
console.log(calculator(subtract, 20, 12, 1)); // -33
console.log(calculator(multiply, 1, 2, 3, 4)); // 24
// 打印JSON数据的 title 属性
function printTitle({ title }) {
console.log(title);
}
const article = {
title: "JavaScript 函数定义",
description: "函数定义方式",
};
printTitle(article); // JavaScript 函数定义

+关注

255

0