这次给大家带来一道面试题,在前端公司的面试过程中注意事项有哪些,下面就是实战案例,一起来看一下。
最近徘徊在找工作和继续留任的纠结之中,在朋友的怂恿下去参加了一次面试,最后一道题目是:
写一个函数,输入一个字符串的运算式,返回计算之后的结果。例如这样的: '1 + (5 - 2) * 3',计算出结果为10
最开始看到这个题目的时候,我脑中的第一反应就是eval
,真的太直接了。但是我就不明白为什么这竟然是最后一道题目,我也不知道为什么还会考eval
的运用,因此当时也很犹豫要不要用eval
。因为eval
有一系列的问题:
eval会改变当前的作用域,除非函数直接调用,并且是
eval
本身执行eval可能会造成xss攻击,除非你对其中的字符串特别放心
当时只是觉得可以使用正则匹配运算符,然后使用递归计算,就只写了个思路,回来之后就按照这个方式实现一下。这里作为自己的解决方式,测试用例设计的也不够全面,如果各位有更好的方法,可以拿出来分享。
如果我拿个'1 + (5 - 2) * 3'这个式子我是怎么想的:
看成 1 + x * 3
算出x,x的计算就需要匹配括号,这个倒不是很难
计算出x之后,替换成 1 + 3 * 3
之后按照
/%*
的优先级要大于+-
,先匹配计算出 3 * 3替换成 1 + 9
最后得出 10
讲白了就是有括号,先计算括号中的算是,然后进行结果替换之后再进行后面的运算,整体而言就是一系列的'递归 + 匹配'。
/** * myEval * @param string str 字符串 * @return 返回计算后的值 [description] */function myEval(str) { // 如果包含括号,则先进括号中的计算 // 计算规则为:先进行括号匹配拆开,单个计算之后再进行拼接 // 例如:((1 + 2) + 3 / (4 % 6)) * 6的计算顺序是: // -> ((1 + 2) + 3 / (4 % 6)) * 6 // -> (1 + 2) + 3 / (4 % 6) // -> 1 + 2 // -> 3 + 3 / (4 % 6) // -> 4 % 6 // -> 3 + 3 / 4 // -> 3 / 4 // -> (3 + 0.75) * 6 // -> 3 + 0.75 // -> 3.75 * 6 // -> 22.5 if (exists(str, '(')) { const bracketStr = getMatchStr(str); const nextResult = myEval(bracketStr); const replaceStr = str.replace(`(${bracketStr})`, nextResult) // 如果子字符串中存在'3 + 3 / (4 % 6)' 这样的式子,说明第一个括号中的内容计算完成了 // 这样就可以接着递归进行第二个括号中的算式计算 if (exists(replaceStr, '(')) { return myEval(replaceStr); } else { // 如果是类似于'1 + 2 / 3'的式子,则直接进行计算返回结果 return innerBracketCacl(replaceStr); } } else { return innerBracketCacl(str); }}
取一个叫做myEval
的函数,主要进行流程的控制,如果遇到的是括号中的内容,则先进行括号中的运算,否则,直接进行常规表达式计算。
/** * 获取匹配的字符串 * @param string str * @return string 返回的匹配结果 */function getMatchStr(str) { // 匹配类似于这样的式子: // '((1 + 2) / 3) * 4' -> ((1 + 2) / 3) // '1 * (2 + 3) / (5 - 6)' -> 2 + 3 const regexp = /\([^\)]+\)[^\(]+\)|\((.*?)\)/; const regexp2 = /\((.*)\)/; let matches = str.match(regexp); let bracketStr = matches[1] || matches[0]; if (exists(bracketStr, '(') && !exists(bracketStr, ')')) { // 类似于这样的式子'((1 + 2) / (3 - 7)) * 4' // 那么匹配出来的就是'(1 + 2' // 显然不是我想要的结果,我只需要解掉第一层的括号就可以按照之前的方式计算了 // 用第二个正则匹配的就是'(1 + 2) / (3 - 7)' // 我只需要按照之前的方式先计算这个式子就好 bracketStr = str.match(regexp2)[1]; } else if(bracketStr.indexOf('(') === 0) { bracketStr = bracketStr.slice(1, -1); } return bracketStr;}
获取匹配字符子串,主要是进行规则匹配,分布计算。
/** * 计算表达式 * 例如有这样的式子: '1 + 2 / 3' * 那么会先计算'2 / 3' * @param string str * @return string 结果 */function innerBracketCacl(str) { const matches = str.match(/[\/\*%]/g); let firstPriorityResult = str; if (matches) { firstPriorityResult = stepFirstPriority(str); } return stepSecondPriority(firstPriorityResult);}
简单的运算式计算,即不包含括号的计算,先计算*/%
的运算符,然后计算+-
/** * 第一优先级的运算 * 这里的第一优先级为'%/*' * @param string str * @return number 返回计算结果 */function stepFirstPriority(str) { const matches = str.match(/[\/\*%]/g); if (!matches) { return str; } else { const newStr = caclPart('/%*', str); return stepFirstPriority(newStr); }}/** * 第二优先级的运算 * 这里的第一优先级为'+-' * @param string str * @return number 返回计算结果 */function stepSecondPriority(str) { if (!isNaN(Number(str))) { return str; } else { const newStr = caclPart('+-', str); return stepSecondPriority(newStr); }}
这上面是运算优先级的计算方式,先乘除后加减,计算之后进行字符串替换,然后递归计算。
/** * 计算类似于 '1 + 2', '3 / 4'的子算式 * @param string shouldOprs 包含的运算符,例如('/%*', '+-') * @param string str 计算的子字符串,例如( 1 + 2 / 4 ) * @return string 返回计算后的子字符串,例如( 1 + 0.5 ) */function caclPart(shouldOprs, str) { let newStr = ''; for (let i = 0; i '3 + 0.75' // 单个计算完成之后跳出循环,之后继续进行后面的操作 const result = cacl(leftNum, rightNum, s); newStr = str.replace(new RegExp('(\\d\\.)*\\d+\\s\*\\' + s + '\\s\*(\\d\\.)*\\d+'), result); break; } } return newStr;}
至此,这就是我的全部思路以及实现方式。
其中有一些正则表达式写不出,想来正则学得还是不够,只能用一些取巧的办法。测试用例也设计得不是太全面,可能会存在一些问题,但是就目前的测试来说,简单的算是是能通过的。
性能问题上:因为频繁的调用递归,致使复杂度大大增大,时间运行得也比原生eval
时间要长。以下是我的测试例子:
const str = '1 + 2';const str2 = '1 + 2 - 3';const str3 = '1 + 2 + 3 / 4';const str4 = '1 + 2 + 3 / 4 % 5';const str5 = '1 + 2 * (3 + 4) + 5';const str6 = '(1 + 2) * (3 + 4) + 5';const str7 = '((1 + 2) + 3 / (4 % 6)) * 6';console.time('myEval');console.log('myEval: ', myEval(str));console.log('myEval: ', myEval(str2));console.log('myEval: ', myEval(str3));console.log('myEval: ', myEval(str4));console.log('myEval: ', myEval(str5));console.log('myEval: ', myEval(str6));console.log('myEval: ', myEval(str7));console.timeEnd('myEval')console.time('eval');console.log('eval: ', eval(str));console.log('eval: ', eval(str2));console.log('eval: ', eval(str3));console.log('eval: ', eval(str4));console.log('eval: ', eval(str5));console.log('eval: ', eval(str6));console.log('eval: ', eval(str7));console.timeEnd('eval')
关于js
实现eval
的方式:
//计算表达式的值function evil(fn) { var Fn = Function; //一个变量指向Function,防止有些前端编译工具报错 return new Fn('return ' + fn)();}// jquery2.0.3实现方式:// Evaluates a script in a global contextglobalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } }}
参考资料:
JavaScript为什么不要使用eval
以eval()和newFunction()执行JavaScript代码
Js代替eval的方法
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
vue plug-in implements mobile carousel image
The above is the detailed content of an interview question. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use
