an interview question
这次给大家带来一道面试题,在前端公司的面试过程中注意事项有哪些,下面就是实战案例,一起来看一下。
最近徘徊在找工作和继续留任的纠结之中,在朋友的怂恿下去参加了一次面试,最后一道题目是:
写一个函数,输入一个字符串的运算式,返回计算之后的结果。例如这样的: '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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
