八个写JavaScript代码的小技巧!
发布时间:2020-11-27
作者:管理员
来源:本站
浏览量(1)
点赞(0)
点踩(0)
评论(0)
收藏(0)
摘要:1. 生成指定区间内的数字有时候需要创建在某个数字范围内的数组。比如在选择生日时。以下是最简单的实现方法。let start = 1900, end = 2000;[...new Array(end + 1).keys()].slice(start);// [ 1900, 1901, ..., 2000]// 也可以这样,但是大范围结果不稳定Array...
let start = 1900, end = 2000; [...new Array(end + 1).keys()].slice(start); // [ 1900, 1901, ..., 2000] // 也可以这样,但是大范围结果不稳定 Array.from({ length: end - start + 1 }, (_, i) => start + i);
const parts = { first: [0, 2], second: [1, 3], }; ["Hello", "World", "JS", "Tricks"].slice(...parts.second); // ["World", "JS", "Tricks"]
// 查到元素中的 y 位置最大的那一个值 const elementsHeight = [...document.body.children].map( el => el.getBoundingClientRect().y ); Math.max(...elementsHeight); // 输出最大的那个值 const numbers = [100, 100, -1000, 2000, -3000, 40000]; Math.min(...numbers); // -3000
const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]; arrays.flat(Infinity); // [ 10, 50, 100, 2000, 3000, 40000 ]
const found = [{ name: "Alex" }].find(i => i.name === 'Jim'); console.log(found.name); // TypeError: Cannot read property 'name' of undefined
const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}; console.log(found.name); // undefined
const makeList = (raw) => raw .join() .trim() .split("\n") .map((s, i) => `${i + 1}. ${s}`) .join("\n"); makeList` Hello, World Hello, World `; // 1. Hello // 2. World
let a = "hello"; let b = "world"; // 错误 ❌ a = b b = a // { a: 'world', b: 'world' } // 正确 ✅ [a, b] = [b, a]; // { a: 'world', b: 'hello' }
const password = "hackme"; password.substr(-3).padStart(password.length, "*"); // ***kme
扫一扫,手机访问
声明:本文由【达扬网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【达扬网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。
下一篇:php生成二维码的两种方法
相关内容
评头论足
现在,非常期待与您的一次邂逅
青海达扬网络传媒有限责任公司努力让每一次邂逅总能超越期待!

嘿,我来帮您!