公司有道面试题是实现计算器的效果,所有面试者都是进行了很复杂的判断来计算的,甚至使用了正则表达式进行验证,其实本题只是考察js基础知识,关于计算只要使用eval()方法就可以得到结果
eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
eval()方法工作中不常用(至少我很少用到),面试者应该是在这样的情况下没有想到该方法而已,下面给出代码,代码中只做了简单的判断,大家使用时可根据需要做调整
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
box-sizing: border-box;
}
.container {
width: 300px;
height: 500px;
background: rgba(255, 167, 167, 0.1);
padding: 25px 15px;
color: #10dada;
}
.showbox {
width: 100%;
height: 50px;
line-height: 50px;
font-size: 25px;
background: #fff;
text-align: right;
padding: 0 10px;
}
.item {
float: left;
width: 58px;
height: 58px;
line-height: 58px;
margin: 4px;
border-radius: 50%;
background: #fff;
text-align: center;
font-size: 20px;
cursor: pointer;
}
.item:hover {
box-shadow: 0 0 3px 3px #eee;
}
.panel {
overflow: hidden;
margin-top: 20px;
}
</style>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="showbox process"></div>
<div class="showbox result"></div>
<div class="panel">
<div class="item">c</div>
<div class="item">(</div>
<div class="item">)</div>
<div class="item">/</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">*</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">-</div>
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">+</div>
<div class="item">0</div>
<div class="item">.</div>
<div class="item">del</div>
<div class="item">=</div>
</div>
</div>
<script>
var process = ''; // 计算式子
var result = ''; // 计算结果
var flag = false; // 是否为显示计算结果状态
$('.panel').on('click', '.item', function (e) {
var text = this.innerHTML; // 获取被点击按钮的文本信息
if (flag) { // 当前为显示结果状态
process = '';
result = '';
flag = false;
}
if (text === 'c') {
process = '';
result = '';
} else if (text === 'del') {
process = process.slice(0, -1);
} else if (text === '=') {
try {
result = eval(process);
} catch (e) {
result = '错误'
}
flag = true;
} else {
process += text;
}
$('.process').html(process);
$('.result').html(result);
})
</script>
</body>
</html>
下面是结果图,分别为正确计算和错误的显示
正确计算结果 计算出错
网友评论