Single lines of code are extremely difficult to maintain (and sometimes even difficult to understand), but that doesn’t stop them from being pretty cool. You will definitely feel satisfied after writing a minimalist solution.
Here are some of my recent favorites. They all run directly in your open console, give it a try. I hope you can share your favorite code in the comments too.
Ali Spittel pushed recent news. It solves a problem I've faced many times. If you replace the minus sign with a plus sign, it gives you the days for the next seven days.
// 创建一个过去七天的数组,包含 [...Array(7).keys()].map(days => new Date(Date.now() - 86400000 * days));
This is my go-to feature for creating unique IDs when prototyping. I've even seen people using it in production mode. It's not safe, but... there are worse random generating functions.
// 生成一个长度为 11 的随机字母字符串 Math.random().toString(36).substring(2);
quine is a program that outputs its own source code. Quine has always fascinated me. I've done my own quine several times in different languages, but it's the details that matter.
I picked some winners for you. These three are from Mama Fun Roll, PleaseStand, and Peter Olson.
// $=_=>`$=${$};$()`;$() $=_=>`$=${$};$()`;$() // eval(I="'eval(I='+JSON.stringify(I)+')'") eval(I="'eval(I='+JSON.stringify(I)+')'") // For those who like their quines via alert // (function a(){alert("("+a+")()")})() (function a(){alert("("+a+")()")})()
This is about unmaintainable code. This converts the page's query parameters into a 78-byte object. Thanks to Alex Lohr for providing code implementation (and Qi Yi).
?foo=bar&baz=bing => {foo: bar, baz: bing}
// 设置 `q` 的值为当前页面的查询参数 q={};location.search.replace(/([^?&=]+)=([^&]*)/g,(_,k,v)=>q[k]=v);q;
I want to see the mini work so hard.
With only a small amount of code, you can create a work alarm clock, and you can read its source code in one go. After a challenge with my colleagues, I wrote this article. It times every second and updates the page with the current time.
<body onload="setInterval(()=>document.body.innerHTML=new Date().toGMTString().slice(17,25))"></body>
Shown in Pythonistas import random
, random.shuffle(array)
Solution Before the plan, we could only fend for ourselves. This has the advantage that the chance of becoming an infinite loop is small (depending on your implementation). Michiel Hendriks Help us save some characters
The above is the detailed content of Share some practical single-line JS codes. For more information, please follow other related articles on the PHP Chinese website!