
最近在学react,没啥时间更新博客,等有空的时候把react基础写一写,react写法还是挺有意思的。
这个实例没啥可说的,就是一个小实例而已,js实现最简单的计算器功能。
当然原理很简单的,就是通过eval()可以计算字符串的特性实现字符串的运算,当然eval()还是少用为好,它的可读性非常差,不好再做优化和编译。
关键js代码
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 | var btns = document.querySelectorAll('button.btns'), text = document.querySelectorAll('.box p'), arr = [], Result; [].slice.call(btns).forEach(function(element) {     element.onclick = function(){                                              if(this.value === '='){             try{             Result = eval('('+arr.join('')+')');             }catch(e){             Result = 'error';             }         arr  = [Result];          text[1].innerText = Result;           }else{             text[0].innerText = '';             if(this.value === 'C'){                 arr = [];                 return;              }                 if(this.value === 'Back'){                 arr.pop();             }else{                 arr.push(this.value);             }                                                          arr.map(function(num){                 text[0].innerText += num;             });         }     } });
 | 
本文代码地址:链接