search
HomeWeb Front-endJS Tutorialan interview question

an interview question

Mar 19, 2018 pm 01:57 PM
test questions

这次给大家带来一道面试题,在前端公司的面试过程中注意事项有哪些,下面就是实战案例,一起来看一下。

最近徘徊在找工作和继续留任的纠结之中,在朋友的怂恿下去参加了一次面试,最后一道题目是:

写一个函数,输入一个字符串的运算式,返回计算之后的结果。例如这样的: '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')

an interview question

关于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中文网其它相关文章!

推荐阅读:

在前端中的html基础知识 

Css float的盒子模型position

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment