简单的用JavaScript实现计算器的方法可以使用eval()函数,该函数可以计算字符串中的数学表达式。以下是一个简单的示例:
html复制代码运行
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>简单计算器</title> </head> <body> <input type="text" id="expression" placeholder="请输入表达式"> <button onclick="calculate()">计算</button> <p>结果:<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("输入的表达式有误,请检查后重新输入"); } } </script> </body> </html>
这个示例中,我们创建了一个简单的HTML页面,包含一个输入框用于输入表达式,一个按钮用于触发计算,以及一个用于显示结果的段落。在JavaScript部分,我们定义了一个名为calculate的函数,该函数首先获取输入框中的表达式,然后使用eval()函数计算表达式的结果,并将结果显示在页面上。如果输入的表达式有误,我们会弹出一个警告框提示用户检查输入。
时在制作页面的时候,总会碰到有的元素是100%的宽度。众所周知,如果元素宽度为100%时,其自身不带其他盒模型属性设置还好,要是有别的,那将导致盒子撑破。比如说,有一个边框,或者说有margin和padding,这些都会让你的盒子撑破。我们换句话来说,如果你的元素宽度是100%时,只要你在元素中添加了border,padding,margin任何一值,都将会把元素盒子撑破(标准模式下,除IE怪异模式)。这样一来就会相当的麻烦,平时我们碰到这样的现象时,也是相当的谨慎,有时甚至无法解决,只能通过改变结构来实现。就算你通过繁琐的方法实现了,但由于浏览器的兼容性而导致最终效果不一致。
虽然前面介绍的CSS3属性中的box-sizing在一定程度上解决这样的问题,其实今天的calc()函数功能实现上面的效果来得更简单。
学习calc()之前,我们有必要先知道calc()是什么?只有知道了他是个什么东东?在实际运用中更好地使用他。
calc()从字面我们可以把他理解为一个函数function。其实calc是英文单词calculate(计算)的缩写,是css3的一个新增的功能,用来指定元素的长度。比如说,你可以使用calc()给元素的border、margin、pading、font-size和width等属性设置动态值。为何说是动态值呢?因为我们使用的表达式来得到的值。不过calc()最大的好处就是用在流体布局上,可以通过calc()计算得到元素的宽度。
calc()能让你给元素的宽度做计算,你可以给一个div元素,使用百分比、em、px和rem单位值计算出其宽度或者高度,比如说“width:calc(50% + 2em)”,这样一来你就不用考虑元素DIV的宽度值到底是多少,而把这个烦人的任务交由浏览器去计算。
calc()语法非常简单,就像我们小时候学加 (+)、减(-)、乘(*)、除(/)一样,使用数学表达式来表示:
.elm { width: calc(expression); }
其中"expression"是一个表达式,用来计算长度的表达式。
calc()使用通用的数学运算规则,但是也提供更智能的功能:
浏览器的兼容性
浏览器对calc()的兼容性还算不错,在IE9+、FF4.0+、Chrome19+、Safari6+都得到较好支持,同样需要在其前面加上各浏览器厂商的识别符,不过可惜的是,移动端的浏览器还没仅有“firefox for android 14.0”支持,其他的全军覆没。大家在实际使用时,同样需要添加浏览器的前缀。
.elm {
/*Firefox*/
-moz-calc(expression);
/*chrome safari*/
-webkit-calc(expression);
/*Standard */
calc(expression);
}
通过上面的了解,大家对calc()不再那么陌生,但对于实际的运用可能还是不太了解,那么大家就接下来跟我一起动手,通过实例来了解他吧。首先我们来看一个最常用的实例:
<div class="demo">
<div class="box"></div>
</div>
上面的结构很简单,就是一个div.demo的元素中包含了一个div.box的元素,接下来我们一步一步来看其中的变化。
第一步:添加普通样式:
.demo {
width: 300px;
background: #60f;
}
.box {
width: 100%;
background: #f60;
height: 50px;
}
此时的效果很简单,就是div.box完全遮盖了div.demo,如下图所示:
第二步,在div.box上添加border和padding
这一步很棘手的事情来了,在div.box上添加10px的内距padding,同时添加5px的border:
.demo {
width: 300px;
background: #60f;
}
.box {
width: 100%;
background: #f60;
height: 50px;
padding: 10px;
border: 5px solid green;
}
为了更好地说明问题,我在div.demo上添加了一个padding:3px 0;
.demo {
width: 300px;
background: #60f;
padding: 3px 0;
}
.box {
width: 100%;
background: #f60;
height: 50px;
padding: 10px;
border: 5px solid green;
}
这个时候大家不知道能否想到问题会发生在哪?其实很简单,这个时候div.box的宽度大于了其容器div.demo的总宽度,从而撑破容器伸出来了,如图所示:
第三步,calc()的运用
为了解决撑破容器的问题,以前我们只能去计算div.box的宽度,用容器宽度减去padding和border的值,但有时候,我们苦于不知道元素的总宽度,比如说是自适应的布局,只知道一个百分值,但其他的值又是px之类的值,这就是难点,死卡住了。随着CSS3的出现,其中利用box-sizing来改变元素的盒模型类型来实现效果,但今天我们学习的calc()方法更是方便。
知道总宽度是100%,在这个基础上减去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()计算后,div.box不会再超出其容器div.demo的宽度,如图所示:
上面是一个简单的实例,接下来我们一起来看一个自适应布局的例子:
这个demo是一个非常简单而常见的布局效果,在这个布局中,我采用了自适应布局。整个布局包含了“头部”、“主内容”、“边栏”和“脚部”,并且“主内容”居左,“边栏”靠右,具体结构请看DEMO中的html部分。
接下来,我们主要看看css部分:
1、在body中设置一个内边距,并附上一些基本的样式,大家可以根据自己需要进行不同的设置,代码如下:
body {
background: #E8EADD;
color: #3C323A;
padding: 20px;
}
2、设置主容器“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()的浏览器设置了一个固定宽度值“1024px”。
3、给header和footer设置样式
这个例子中的header和footer很简单,给他们添加了一个内距为20px,其他就是一些基本的样式设置,那么其对应的宽度应该是"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、给主内容设置样式
给主内容设置了一个8px的边框,20px的内距,并且向左浮动,同时设置了一个向右的外边距“20”px,关键之处,我们主内容占容器宽度的75%,这样一来,主内容的宽度应该是“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、设置右边栏样式
给边栏设置了一个25%的宽度,其除了包含8px的边框,10px的内距外,还有主内容外距20px也要去掉,不然整个宽度与容器会相差20px,换句话说就会撑破容器掉下来。因此边栏的实际宽度应该是"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展现的布局效果。经过此例的学习,大家是不是会觉得使用calc()用于自适应布局是超爽的呀。此时有很多同学肯定会感吧,苦逼的IE6-8不支持,不敢使用。
最后附上兼容性示意图:
日常 Web 开发中,书写代码遵循的原则是用尽可能少的代码实现尽可能多的功能。本文将探索日常开发中遇到的需求场景,仅用一行代码来实现。
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'}}])
由于是浅拷贝,嵌套对象或数组将通过引用拷贝,而不是复制。
const isEmptyArray=arr=> Array.isArray(arr) && !arr.length;
// recommend
const isEmptyArray=({ length })=> length===0;
// output: true
isEmptyArray(Array(2))
({ length })=> length===0 被大多数开发者所推荐,关于是否是数组应该再另一个函数中判断,遵循“函数单一职责原则”。
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}])
请注意:代码仅适用于具有原始值(string、number、bigint、boolean、undefined、symbol 和 null)的元素。保留元素的顺序并返回数组的副本。
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标准定义了每个字符的性质,许多支持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()}));
以上就是我们开发中经常遇到的场景,都可以用一行代码来实现。如果你还有其他的 一行代码实现的逆天操作 欢迎留言讨论。
*请认真填写需求信息,我们会在24小时内与您取得联系。