javascript
Some Essential JavaScript Questions And Answers(5)
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)函數(shù)用于決定x是不是整數(shù),討論可行的方法有哪些。
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() 函數(shù)。然而,在ECMAScript 6 之前,會更復(fù)雜一點,因為沒有提供類似于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規(guī)格說明中,整數(shù)只是概念上存在:即,數(shù)值總是以浮點型值的形式存儲。
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之前最簡單最干凈的解決方法是(即使一個非數(shù)字的值比如如字符串或null被傳遞給函數(shù),也會文件地返回false)使用按位異或操作:
function isInteger(x) { return (x ^ 0) === x; }The following solution would also work, although not as elegant as the one above:
[譯]:以下這種方法也是可行的,雖然沒有上面那種那么優(yōu)雅:
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.
[譯]:注意,上述實現(xiàn)中,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函數(shù)為基礎(chǔ)的方法在很多不同的x下都是正確的,但x 取值相當(dāng)大時,就會無法正常工作,問題在于 parseInt() 在解析數(shù)字之前強制其第一個參數(shù)為字符串(提示:即數(shù)字太大,轉(zhuǎn)成了科學(xué)計數(shù)法形式,是一個字符串)。因此,一旦數(shù)目變得足夠大,它的字符串就會表達為指數(shù)形式(例如, 1e+21)。因此,parseInt() 函數(shù)就會去解析 1e+21,當(dāng)解析到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?
[譯]:下列代碼執(zhí)行時,數(shù)字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:
[譯]:數(shù)值將以以下順序輸出
1 4 3 2Let’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()調(diào)用,沒有任何延遲。
-
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不是應(yīng)該在4之前輸出嗎?
The answer has to do with properly understanding?JavaScript events and timing.
[譯]:要回答這個問題,你需要正確理解JavaScript的事件和時間設(shè)置。
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).
[譯]:瀏覽器有一個事件循環(huán),會檢查事件隊列和處理未完成的事件。例如,如果瀏覽器正忙(例如,處理一個 onclick)的時候,在后臺發(fā)生了一個事件(例如,腳本的 onload 事件),那么事件會添加到隊列中。當(dāng)onclick處理程序完成后,檢查隊列,然后處理該事件(例如,執(zhí)行 onload 腳本)。
Similarly,?setTimeout()?also puts execution of its referenced function into the event queue if the browser is busy.
[譯]:同理,如果瀏覽器正忙的話,setTimeout() 也會把其引用的函數(shù)的執(zhí)行放到事件隊列中。
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).
?
[譯]:當(dāng)setTimeout()的第二個參數(shù)為0的時候,它的意思是“盡快”執(zhí)行指定的函數(shù)。具體而言,函數(shù)的執(zhí)行會放置在事件隊列的下一個計時器開始。注意,雖然如此,但這不是立即執(zhí)行:函數(shù)不會被執(zhí)行除非下一個計時器開始。這就是為什么在上述的例子中,調(diào)用 console.log(4) 發(fā)生在調(diào)用 console.log(3) 之前(因為調(diào)用 console.log(3) 是通過setTimeout被調(diào)用的,因此會稍微延遲)。
?
總結(jié)
以上是生活随笔為你收集整理的Some Essential JavaScript Questions And Answers(5)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 东北话上头是什么意思
- 下一篇: 表达喜欢一个人的句子 形容爱到骨子里的句