簡單的用JavaScript實(shí)現(xiàn)計(jì)算器的方法可以使用eval()函數(shù),該函數(shù)可以計(jì)算字符串中的數(shù)學(xué)表達(dá)式。以下是一個(gè)簡單的示例:
html復(fù)制代碼運(yùn)行
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>簡單計(jì)算器</title> </head> <body> <input type="text" id="expression" placeholder="請(qǐng)輸入表達(dá)式"> <button onclick="calculate()">計(jì)算</button> <p>結(jié)果:<span id="result"></span></p> <script> function calculate() { var expression=document.getElementById("expression").value; try { var result=eval(expression); document.getElementById("result").innerText=result; } catch (error) { alert("輸入的表達(dá)式有誤,請(qǐng)檢查后重新輸入"); } } </script> </body> </html>
這個(gè)示例中,我們創(chuàng)建了一個(gè)簡單的HTML頁面,包含一個(gè)輸入框用于輸入表達(dá)式,一個(gè)按鈕用于觸發(fā)計(jì)算,以及一個(gè)用于顯示結(jié)果的段落。在JavaScript部分,我們定義了一個(gè)名為calculate的函數(shù),該函數(shù)首先獲取輸入框中的表達(dá)式,然后使用eval()函數(shù)計(jì)算表達(dá)式的結(jié)果,并將結(jié)果顯示在頁面上。如果輸入的表達(dá)式有誤,我們會(huì)彈出一個(gè)警告框提示用戶檢查輸入。
時(shí)在制作頁面的時(shí)候,總會(huì)碰到有的元素是100%的寬度。眾所周知,如果元素寬度為100%時(shí),其自身不帶其他盒模型屬性設(shè)置還好,要是有別的,那將導(dǎo)致盒子撐破。比如說,有一個(gè)邊框,或者說有margin和padding,這些都會(huì)讓你的盒子撐破。我們換句話來說,如果你的元素寬度是100%時(shí),只要你在元素中添加了border,padding,margin任何一值,都將會(huì)把元素盒子撐破(標(biāo)準(zhǔn)模式下,除IE怪異模式)。這樣一來就會(huì)相當(dāng)?shù)穆闊綍r(shí)我們碰到這樣的現(xiàn)象時(shí),也是相當(dāng)?shù)闹?jǐn)慎,有時(shí)甚至無法解決,只能通過改變結(jié)構(gòu)來實(shí)現(xiàn)。就算你通過繁瑣的方法實(shí)現(xiàn)了,但由于瀏覽器的兼容性而導(dǎo)致最終效果不一致。
雖然前面介紹的CSS3屬性中的box-sizing在一定程度上解決這樣的問題,其實(shí)今天的calc()函數(shù)功能實(shí)現(xiàn)上面的效果來得更簡單。
學(xué)習(xí)calc()之前,我們有必要先知道calc()是什么?只有知道了他是個(gè)什么東東?在實(shí)際運(yùn)用中更好地使用他。
calc()從字面我們可以把他理解為一個(gè)函數(shù)function。其實(shí)calc是英文單詞calculate(計(jì)算)的縮寫,是css3的一個(gè)新增的功能,用來指定元素的長度。比如說,你可以使用calc()給元素的border、margin、pading、font-size和width等屬性設(shè)置動(dòng)態(tài)值。為何說是動(dòng)態(tài)值呢?因?yàn)槲覀兪褂玫谋磉_(dá)式來得到的值。不過calc()最大的好處就是用在流體布局上,可以通過calc()計(jì)算得到元素的寬度。
calc()能讓你給元素的寬度做計(jì)算,你可以給一個(gè)div元素,使用百分比、em、px和rem單位值計(jì)算出其寬度或者高度,比如說“width:calc(50% + 2em)”,這樣一來你就不用考慮元素DIV的寬度值到底是多少,而把這個(gè)煩人的任務(wù)交由瀏覽器去計(jì)算。
calc()語法非常簡單,就像我們小時(shí)候?qū)W加 (+)、減(-)、乘(*)、除(/)一樣,使用數(shù)學(xué)表達(dá)式來表示:
.elm { width: calc(expression); }
其中"expression"是一個(gè)表達(dá)式,用來計(jì)算長度的表達(dá)式。
calc()使用通用的數(shù)學(xué)運(yùn)算規(guī)則,但是也提供更智能的功能:
瀏覽器的兼容性
瀏覽器對(duì)calc()的兼容性還算不錯(cuò),在IE9+、FF4.0+、Chrome19+、Safari6+都得到較好支持,同樣需要在其前面加上各瀏覽器廠商的識(shí)別符,不過可惜的是,移動(dòng)端的瀏覽器還沒僅有“firefox for android 14.0”支持,其他的全軍覆沒。大家在實(shí)際使用時(shí),同樣需要添加瀏覽器的前綴。
.elm {
/*Firefox*/
-moz-calc(expression);
/*chrome safari*/
-webkit-calc(expression);
/*Standard */
calc(expression);
}
通過上面的了解,大家對(duì)calc()不再那么陌生,但對(duì)于實(shí)際的運(yùn)用可能還是不太了解,那么大家就接下來跟我一起動(dòng)手,通過實(shí)例來了解他吧。首先我們來看一個(gè)最常用的實(shí)例:
<div class="demo">
<div class="box"></div>
</div>
上面的結(jié)構(gòu)很簡單,就是一個(gè)div.demo的元素中包含了一個(gè)div.box的元素,接下來我們一步一步來看其中的變化。
第一步:添加普通樣式:
.demo {
width: 300px;
background: #60f;
}
.box {
width: 100%;
background: #f60;
height: 50px;
}
此時(shí)的效果很簡單,就是div.box完全遮蓋了div.demo,如下圖所示:
第二步,在div.box上添加border和padding
這一步很棘手的事情來了,在div.box上添加10px的內(nèi)距padding,同時(shí)添加5px的border:
.demo {
width: 300px;
background: #60f;
}
.box {
width: 100%;
background: #f60;
height: 50px;
padding: 10px;
border: 5px solid green;
}
為了更好地說明問題,我在div.demo上添加了一個(gè)padding:3px 0;
.demo {
width: 300px;
background: #60f;
padding: 3px 0;
}
.box {
width: 100%;
background: #f60;
height: 50px;
padding: 10px;
border: 5px solid green;
}
這個(gè)時(shí)候大家不知道能否想到問題會(huì)發(fā)生在哪?其實(shí)很簡單,這個(gè)時(shí)候div.box的寬度大于了其容器div.demo的總寬度,從而撐破容器伸出來了,如圖所示:
第三步,calc()的運(yùn)用
為了解決撐破容器的問題,以前我們只能去計(jì)算div.box的寬度,用容器寬度減去padding和border的值,但有時(shí)候,我們苦于不知道元素的總寬度,比如說是自適應(yīng)的布局,只知道一個(gè)百分值,但其他的值又是px之類的值,這就是難點(diǎn),死卡住了。隨著CSS3的出現(xiàn),其中利用box-sizing來改變?cè)氐暮心P皖愋蛠韺?shí)現(xiàn)效果,但今天我們學(xué)習(xí)的calc()方法更是方便。
知道總寬度是100%,在這個(gè)基礎(chǔ)上減去boder的寬度(5px * 2=10px),再減去padding的寬度(10px * 2=20px),即“100% - (10px + 5px) * 2=30px” ,最終得到的值就是div.box的width值:
.demo {
width: 300px;
background: #60f;
padding: 3px 0;
}
.box {
background: #f60;
height: 50px;
padding: 10px;
border: 5px solid green;
width: 90%;/*寫給不支持calc()的瀏覽器*/
width:-moz-calc(100% - (10px + 5px) * 2);
width:-webkit-calc(100% - (10px + 5px) * 2);
width: calc(100% - (10px + 5px) * 2);
}
這樣一來,通過calc()計(jì)算后,div.box不會(huì)再超出其容器div.demo的寬度,如圖所示:
上面是一個(gè)簡單的實(shí)例,接下來我們一起來看一個(gè)自適應(yīng)布局的例子:
這個(gè)demo是一個(gè)非常簡單而常見的布局效果,在這個(gè)布局中,我采用了自適應(yīng)布局。整個(gè)布局包含了“頭部”、“主內(nèi)容”、“邊欄”和“腳部”,并且“主內(nèi)容”居左,“邊欄”靠右,具體結(jié)構(gòu)請(qǐng)看DEMO中的html部分。
接下來,我們主要看看css部分:
1、在body中設(shè)置一個(gè)內(nèi)邊距,并附上一些基本的樣式,大家可以根據(jù)自己需要進(jìn)行不同的設(shè)置,代碼如下:
body {
background: #E8EADD;
color: #3C323A;
padding: 20px;
}
2、設(shè)置主容器“wrapper”的樣式
主容器的寬度是“100% - 20px * 2”,并且水平居中:
.wrapper {
width: 1024px; /*寫給不支持calc()的瀏覽器*/
width: -moz-calc(100% - 40px);
width: -webkit-calc(100% - 40px);
width: calc(100% - 40px);
margin: auto;
}
給不支持calc()的瀏覽器設(shè)置了一個(gè)固定寬度值“1024px”。
3、給header和footer設(shè)置樣式
這個(gè)例子中的header和footer很簡單,給他們添加了一個(gè)內(nèi)距為20px,其他就是一些基本的樣式設(shè)置,那么其對(duì)應(yīng)的寬度應(yīng)該是"100% - 20px * 2":
#header {
background: #f60;
padding: 20px;
width: 984px;/*寫給不支持calc()的瀏覽器*/
width: -moz-calc(100% - 40px);
width: -webkit-calc(100% - 40px);
width: calc(100% - 40px);
}
#footer {
clear:both;
background: #000;
padding: 20px;
color: #fff;
width: 984px;/*寫給不支持calc()的瀏覽器*/
width: -moz-calc(100% - 40px);
width: -webkit-calc(100% - 40px);
width: calc(100% - 40px);
}
4、給主內(nèi)容設(shè)置樣式
給主內(nèi)容設(shè)置了一個(gè)8px的邊框,20px的內(nèi)距,并且向左浮動(dòng),同時(shí)設(shè)置了一個(gè)向右的外邊距“20”px,關(guān)鍵之處,我們主內(nèi)容占容器寬度的75%,這樣一來,主內(nèi)容的寬度應(yīng)該是“75% - 8px * 2 - 20px * 2”:
#main {
border: 8px solid #B8C172;
float: left;
margin-bottom: 20px;
margin-right: 20px;
padding: 20px;
width: 704px;/*寫給不支持calc()的瀏覽器*/
width: -moz-calc(75% - 20px * 2 - 8px * 2);
width: -webkit-calc(75% - 20px * 2 - 8px * 2);
width: calc(75% - 20px * 2 - 8px * 2);
}
5、設(shè)置右邊欄樣式
給邊欄設(shè)置了一個(gè)25%的寬度,其除了包含8px的邊框,10px的內(nèi)距外,還有主內(nèi)容外距20px也要去掉,不然整個(gè)寬度與容器會(huì)相差20px,換句話說就會(huì)撐破容器掉下來。因此邊欄的實(shí)際寬度應(yīng)該是"25% - 10px * 2 - 8px * 2 -20px":
#accessory {
border: 8px solid #B8C172;
float: right;
padding: 10px;
width: 208px;/*寫給不支持calc()的瀏覽器*/
width: -moz-calc(25% - 10px * 2 - 8px * 2 - 20px);
width: -webkit-calc(25% - 10px * 2 - 8px * 2 - 20px);
width: calc(25% - 10px * 2 - 8px * 2 - 20px);
}
這樣一來,大家就看到了上面demo展現(xiàn)的布局效果。經(jīng)過此例的學(xué)習(xí),大家是不是會(huì)覺得使用calc()用于自適應(yīng)布局是超爽的呀。此時(shí)有很多同學(xué)肯定會(huì)感吧,苦逼的IE6-8不支持,不敢使用。
最后附上兼容性示意圖:
日常 Web 開發(fā)中,書寫代碼遵循的原則是用盡可能少的代碼實(shí)現(xiàn)盡可能多的功能。本文將探索日常開發(fā)中遇到的需求場(chǎng)景,僅用一行代碼來實(shí)現(xiàn)。
const occurrenceMap=arr=> arr.reduce((acc, current)=> (acc[current]=(acc[current] || 0) + 1, acc), {});
// output: { a: 2, b: 1, c: 1, d: 1 }
occurrenceMap(['a', 'b', 'c', 'a', 'd'])
const shallowClone=arr=> arr.slice(0);
// or
const shallowClone=array=> [...array];
// output: [ { a: 'b', b: { c: 'd' } } ]
shallowClone([{a: 'b', b: {c: 'd'}}])
由于是淺拷貝,嵌套對(duì)象或數(shù)組將通過引用拷貝,而不是復(fù)制。
const isEmptyArray=arr=> Array.isArray(arr) && !arr.length;
// recommend
const isEmptyArray=({ length })=> length===0;
// output: true
isEmptyArray(Array(2))
({ length })=> length===0 被大多數(shù)開發(fā)者所推薦,關(guān)于是否是數(shù)組應(yīng)該再另一個(gè)函數(shù)中判斷,遵循“函數(shù)單一職責(zé)原則”。
const removeDuplicates=arr=> [...new Set(arr)];
// output: [ 'a', 'b' ]
removeDuplicates(['a', 'b', 'a'])
// output: [ { a: 1 }, 'b', { a: 1 } ],包含非原始值
removeDuplicates([{a: 1}, 'b', {a: 1}])
請(qǐng)注意:代碼僅適用于具有原始值(string、number、bigint、boolean、undefined、symbol 和 null)的元素。保留元素的順序并返回?cái)?shù)組的副本。
const lowestNumber=arr=> Math.min(...arr);
const biggestNumber=arr=> Math.max(...arr);
// output: 1
lowestNumber([1, 2, 3, 1])
// output: 3
biggestNumber([1, 2, 3, 1])
const closestNumber=(arr, number)=> arr.reduce((acc, current)=> (Math.abs(current - number) < Math.abs(acc - number) ? current : acc) );
// output: 3
closestNumber([1, 2, 3, 4, 1], 3.2)
const indexOfLowestNumber=arr=> arr.indexOf(Math.min(...arr));
const indexOfBiggestNumber=arr=> arr.indexOf(Math.max(...arr));
// output: 0
indexOfLowestNumber([1, 2, 3, 4])
// output: 3
indexOfBiggestNumber([1, 2, 3, 4])
const splitInHalf=arr=> [arr.slice(0, Math.ceil(arr.length / 2)), arr.slice(Math.ceil(arr.length / 2))];
// output: [[1, 2], [3, 4]]
splitInHalf([1,2,3,4])
const longestString=arr=> arr.reduce((prev, curr)=> prev.length > curr.length ? prev : curr);
const shortestString=arr=> arr.reduce((prev, curr)=> prev.length < curr.length ? prev : curr);
// output: abc
console.log(shortestString(['hello', 'fedlab', 'abc']));
// output: fedlab
console.log(longestString(['hello', 'fedlab', 'abc']));
此代碼還能通過返回值的 length 屬性獲取到最短、最長字符串的長度。
const sum=arr=> arr.reduce((a, b)=> a + b, 0);
const average=arr=> arr.reduce((a, b)=> a + b) / arr.length
const shuffle=arr=> [...arr].sort(()=> 0.5 - Math.random());
const toCamelCase=str=> str.replace(/[\s\._-]+\w/g, (m)=> m[m.length-1].toUpperCase());
// output: helloWorld
toCamelCase('hello-world')
toCamelCase('hello world')
toCamelCase('hello_world')
toCamelCase('hello.world')
const toPascalCase=str=> str.replace(/[\s\._-]+\w/g, (m)=> m[m.length - 1].toUpperCase()).replace(str.charAt(0), str.charAt(0).toUpperCase());
// output: HelloWorld
toPascalCase('hello-world')
toPascalCase('hello world')
toPascalCase('hello_world')
toPascalCase('hello.world')
const htmlSpecialChars=str=> str.replace(/[&"'<>]/g, (i)=> ({ "&": "&", '"': """, "'": "'", "<": "<", ">": ">" }[i]));
const reverseWords=(str)=> str.replace(/(\p{L}+)/gu, (word)=> [...word].reverse().join(''));
// output: olleh dlrow
reverseWords('hello world')
Unicode標(biāo)準(zhǔn)定義了每個(gè)字符的性質(zhì),許多支持Unicode的程序能夠通過\p{quality}來支持其中的一部分。
const reverseString=str=> [...str].reverse().join("");
const truncateAfterWord=(str, chars, placeholder='…')=> str.length < chars ? str : `${str.substr( 0, str.substr(0, chars - placeholder.length).lastIndexOf(" "))}${placeholder}`
// output: foo bar…
truncateAfterWord('foo bar baz', 9)
520 表白可以用一下子哈。
const readline=require("readline");function genMonospacedAlphabet(e){return{" ":" ",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z","!":"!","@":"@","#":"#",$:"$","%":"%","^":"^","&":"&","*":"*","(":"(",")":")",_:"_","+":"+"}[e]}const rl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question("Say something: ",(e=>{rl.close();const t=e.split("").map((e=>genMonospacedAlphabet(e))).join(""),s=Math.pow,n=e=>new Promise((t=>{setTimeout((()=>{t()}),e)})),o=genMonospacedAlphabet(" "),a=(()=>{let e=-1,s=t.length;return()=>(e>s-1?e=0:e++,e===s||/\s/.test(t[e])?o:t[e])})(),r=async(e,t)=>{await process.stdout.write(((e,t,n=1,o=1)=>s(s(e*n*.05,2)+s(-t*o*.1,2)-1,3)-s(e*n*.05,2)*s(-t*o*.1,3)<0)(e,t,1.2)?"[91m"+a():o)};let i=-15;const c=async()=>{for(let e=-25;e<25;e+=1)await r(e,i),await n(2);process.stdout.write("\n"),i<10&&(i++,c())};c()}));
以上就是我們開發(fā)中經(jīng)常遇到的場(chǎng)景,都可以用一行代碼來實(shí)現(xiàn)。如果你還有其他的 一行代碼實(shí)現(xiàn)的逆天操作 歡迎留言討論。
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。