Home Web Front-end JS Tutorial an 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);
  }}
Copy after login

取一个叫做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;}
Copy after login

获取匹配字符子串,主要是进行规则匹配,分布计算。

/** * 计算表达式 * 例如有这样的式子: '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);}
Copy after login

简单的运算式计算,即不包含括号的计算,先计算*/%的运算符,然后计算+-

/** * 第一优先级的运算 * 这里的第一优先级为'%/*' * @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);
  }}
Copy after login

这上面是运算优先级的计算方式,先乘除后加减,计算之后进行字符串替换,然后递归计算。

/** * 计算类似于 '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;}
Copy after login

至此,这就是我的全部思路以及实现方式。

其中有一些正则表达式写不出,想来正则学得还是不够,只能用一些取巧的办法。测试用例也设计得不是太全面,可能会存在一些问题,但是就目前的测试来说,简单的算是是能通过的。

性能问题上:因为频繁的调用递归,致使复杂度大大增大,时间运行得也比原生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')
Copy after login

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 );
        }
    }}
Copy after login

参考资料:

  • 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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles