Some Essential JavaScript Questions And Answers

Question 9:

Discuss possible ways to write a function isInteger(x) that determines if x is an integer.

[译]:写一个isInteger(x)函数用于决定x是不是整数,讨论可行的方法有哪些。

Answer:

This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger() method is provided.

[译]:这可能听起来小菜一碟,但事实上,琐碎是因为ECMAScript 6 引入了一个新的正以此为目的 Number.isInteger() 函数。然而,在ECMAScript 6 之前,会更复杂一点,因为没有提供类似于Number.isInteger()的方法。

The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.

[译]:问题是,在ECMAScript规格说明中,整数只是概念上存在:即,数值总是以浮点型值的形式存储。

With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following use of the bitwise XOR operator:

[译]:考虑到这一点,在ECMAScript6之前最简单最干净的解决方法是(即使一个非数字的值比如如字符串或null被传递给函数,也会文件地返回false)使用按位异或操作:

function isInteger(x) { return (x ^ 0) === x; } 

The following solution would also work, although not as elegant as the one above:

[译]:以下这种方法也是可行的,虽然没有上面那种那么优雅:

function isInteger(x) { return Math.round(x) === x; }

Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.

[译]:注意,上述实现中,Math.ceil()与Math.floor()与Math.round()是等价的,可以取代Math.round()。

Or alternatively:

[译]:或者:

function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

One fairly common incorrect solution is the following:

[译]:一个很普遍的不正确的解决方案如下:

function isInteger(x) { return parseInt(x, 10) === x; }

While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:

[译]:虽然这个以 parseInt函数为基础的方法在很多不同的x下都是正确的,但x 取值相当大时,就会无法正常工作,问题在于 parseInt() 在解析数字之前强制其第一个参数为字符串(提示:即数字太大,转成了科学计数法形式,是一个字符串)。因此,一旦数目变得足够大,它的字符串就会表达为指数形式(例如, 1e+21)。因此,parseInt() 函数就会去解析 1e+21,当解析到e字符的时候,就会停止解析,因此只会返回值 1。注意:

> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false

Question 10:

In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?

[译]:下列代码执行时,数字1-4会以什么顺序输出到控制台?为什么?

(function() {console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4);
})();

Answer:

The values will be logged in the following order:

[译]:数值将以以下顺序输出

1
4
3
2

Let’s first explain the parts of this that are presumably more obvious:

[译]:让我们先来解释解释显而易见的那部分:

  • 1 and 4 are displayed first since they are logged by simple calls to console.log() without any delay

  • [译]:1和4首先被显示,是因为它们只是简单地被console.log()调用,没有任何延迟。

  • 2 is displayed after 3 because 2 is being logged after a delay of 1000 msecs (i.e., 1 second) whereas 3 is being logged after a delay of 0 msecs.

  • [译]:2比3显示得迟,是因为2在1000ms(即,1秒)后才输出,而3是在0ms后输出。

OK, fine. But if 3 is being logged after a delay of 0 msecs, doesn’t that mean that it is being logged right away? And, if so, shouldn’t it be logged before 4, since 4 is being logged by a later line of code?

[译]:好吧。但是如果3是在0ms后就被输出的话,意思难道不是立刻打印吗?如果这样的话,输出4的代码在输出3的后边,3不是应该在4之前输出吗?

The answer has to do with properly understanding JavaScript events and timing.

[译]:要回答这个问题,你需要正确理解JavaScript的事件和时间设置。

The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload event) while the browser is busy (e.g., processing an onclick), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload script is executed).

[译]:浏览器有一个事件循环,会检查事件队列和处理未完成的事件。例如,如果浏览器正忙(例如,处理一个 onclick)的时候,在后台发生了一个事件(例如,脚本的 onload 事件),那么事件会添加到队列中。当onclick处理程序完成后,检查队列,然后处理该事件(例如,执行 onload 脚本)。

Similarly, setTimeout() also puts execution of its referenced function into the event queue if the browser is busy.

[译]:同理,如果浏览器正忙的话,setTimeout() 也会把其引用的函数的执行放到事件队列中。

When a value of zero is passed as the second argument to setTimeout(), it attempts to execute the specified function “as soon as possible”. Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That’s why in the above example, the call to console.log(4) occurs before the call to console.log(3) (since the call to console.log(3) is invoked via setTimeout, so it is slightly delayed).

[译]:当setTimeout()的第二个参数为0的时候,它的意思是“尽快”执行指定的函数。具体而言,函数的执行会放置在事件队列的下一个计时器开始。注意,虽然如此,但这不是立即执行:函数不会被执行除非下一个计时器开始。这就是为什么在上述的例子中,调用 console.log(4) 发生在调用 console.log(3) 之前(因为调用 console.log(3) 是通过setTimeout被调用的,因此会稍微延迟)。

Some Essential JavaScript Questions And Answers(5)相关推荐

  1. Some Essential JavaScript Questions And Answers(6)

    Some Essential JavaScript Questions And Answers Question11: Write a simple function (less than 160 c ...

  2. Some Essential JavaScript Questions And Answers(4)

    Some Essential JavaScript Questions And Answers Question7: What is NaN? What is its type? How can yo ...

  3. Some Essential JavaScript Questions And Answers(3)

    Some Essential JavaScript Questions And Answers Question5: What is the significance, and what are th ...

  4. Some Essential JavaScript Questions And Answers(2)

    Some Essential JavaScript Questions And Answers Question3: What will the code below output to the co ...

  5. Some Essential JavaScript Questions And Answers(1)

    一些很经典的JavaScript探讨题,分享分享,英语好的可以忽略我的翻译. Some Essential JavaScript  Questions [译]:一些必要的(基本的)JS面试题及答案 Q ...

  6. mega_[MEGA DEAL] 2018 Essential JavaScript编码捆绑包(96%折扣)

    mega 学习世界上最重要的Web开发语言的终极指南(超过29小时,超过900页!) 嘿,怪胎, 本周,在我们的JCG Deals商店中,我们提供了另一个超值优惠. 我们将在2018 Essentia ...

  7. 35+ Top Apache Tomcat Interview Questions And Answers【转】

    原文地址:https://www.softwaretestinghelp.com/apache-tomcat-interview-questions/ Most frequently asked Ap ...

  8. [笔记一]Essential JavaScript Design Patterns For Beginners

    最近在看Essential JavaScript Design Patterns For Beginners 原文地址:http://www.addyosmani.com/resources/esse ...

  9. C# Interview Questions and Answers

    What's C# ?C# (pronounced C-sharp) is a new object oriented language from Microsoft and is derived f ...

最新文章

  1. 皮一皮:是不是年轻时候的你...
  2. Java基础day3
  3. jdba怎么连接mysql_一、JAVA通过JDBC连接mysql数据库(连接)
  4. Perl split字符串分割函数用法指南
  5. 你可能不知道的package.json
  6. 数据库 索引、存储、引擎这几个的优缺点
  7. 域名实名认证多长时间_域名如何选择有利于网站优化?
  8. Oracle 抄袭亚马逊的 API 是侵权吗?
  9. 赛道对比测试高尔夫6/7 全面解析后悬架
  10. C++ Primer Plus学习(九)——内存模型和名称空间
  11. sqlite3简单使用
  12. u8系统怎么进服务器取数,u8服务器如何连接数据库
  13. 锐捷设备AC旁挂核心交换机①
  14. 普通IO口模拟实现SPI通信及应用解析
  15. 结构体定义 typedef struct LNode 用法说明
  16. 赵小楼《天道》《遥远的救世主》深度解析(123)价格战的目的:是分一杯羹,不是吃肉
  17. SOLIDWORKS+CAD+UG软件培训 三款电脑学习软件
  18. 大功率高精度恒流源的设计
  19. python中fun函数求1+2…+n_功能:编写函数fun求1!+2!+3!+ …… +n!的和,在main函 数中由键盘输入n值,并输出运算结果。请编写fun 函数...
  20. Android UI 绘制流程及原理

热门文章

  1. ElasticSearch学习资料
  2. Elasticsearch的Scroll操作
  3. cURL在Web渗透测试中的应用
  4. 用友BQ商业智能平台——图表功能
  5. OpenCV 中文wiki
  6. CCF201503-1 图像旋转(100分)
  7. centos yum安装python2.7及常见报错处理
  8. JS和OC交互的简单应用
  9. [整理+原创]ubuntu Thunderbird Mail设置自动提醒
  10. sip-selvet 环境搭建