為您的前端/網絡編碼訪談學習JavaScript的有趣方法。所有問題在此處都在文本中回答,並且在我們的YouTube頻道上也有一個視頻。單擊
隨時在我們的社交平台上與我們聯繫! ?
不和諧|| Instagram || Twitter || tiktok ||博客|| Facebook
支持
請配進這個項目,並與其他人分享以表示您的支持。關注我❤️以獲取有關未來項目和教程的最新信息!
語言基礎 - 數組 - 日期和時間 - 面向對象的JavaScript-模塊 - 其他
console . log ( new Date ( 2023 , 1 , 31 ) )Tue Jan 31 2024Tue Jan 31 2023Fri Mar 03 2023Error在JavaScript中,使用日期對象構建日期時,幾個月為0。這意味著0是1月份,1是2月。
因此,在這種情況下,我們要求JavaScript設置2月31日2023的日期,而不存在。
但是,JavaScript無需丟棄錯誤,而將其溢出到下個月的三月。
自2023年2月以來,只有28天,該代碼將在3天之前溢出,結果為2023年3月3日。
var username = 'kirandash'
var username = 'bgwebagency'
console . log ( username )bgwebagencykirandashReferenceErrorSyntaxError我們可以使用var關鍵字多次聲明相同的變量。並且變量將保留其最終分配的值。
但是我們無法使用let或const多次聲明相同的變量
const user = {
username : 'kirandash' ,
updateUsername : newName => {
this . username = newName
} ,
}
user . updateUsername ( 'bgwebagency' )
console . log ( user . username )bgwebagencyReferenceErrorkirandashundefined因為updateUsername函數無法正常工作,並且無法更新user的username 。
用戶object中的updateUsername函數是箭頭函數,不綁定到user對象。
因此, this關鍵字內部updateUsername函數不是指user對象,而是指全局範圍。
要解決此問題,我們應該將箭頭功能更改為正常功能。
const len1 = 'kiran' . length
const len2 = '?' . length
console . log ( len1 , len2 )5, 25, 15, undefined5, SyntaxError在JavaScript中,字符串長度屬性返回字節數,而不是我們預期的字符數。
表情符號是一個Unicode字符,用兩個字節編碼。因此,答案為2。
kiran的字符串長度返回5因為在字符串中,每個字符是1個字節。
console . log ( undefined == null , undefined === null )true, truetrue, falsefalse, falsefalse, true首先,讓我解釋相等和嚴格的平等運營商之間的區別。
相等的操作員僅檢查兩個值是否相等。嚴格的平等運算符檢查值和類型是否相等。
因此,在此代碼中,第一個語句undefined == null返回true因為undefined和null都具有空為空的值。
但是第二個語句undefined === null返回false 。由於typeof undefined是undefined ,而typeof null是object 。
您可能想知道,當null基本上是原始數據類型時,為什麼typeof null為object 。從一開始,這基本上是JavaScript中的一個錯誤。
現在,還有一個建議您:當您要為變量設置一個空值時,使用null而不是undefined 。由於undefined主要用於檢查變量是否沒有分配的值。
function getFruits ( x , ... multi , y ) {
console . log ( x , y , multi ) ;
}
getFruits ( "?" , "?" , "?" , "?" , "?" )? ? ["?", "?", "?"]SyntaxError將REST操作員添加為ES6功能的一部分。
它將所有參數傳遞給函數並將其放在數組中。
如果將多個參數傳遞給函數,則REST操作員必須在末尾出現。這就是為什麼此代碼片段會出現錯誤的原因。
要解決此問題,請將其餘操作員移至最後,然後將其起作用。
let x = Number . NEGATIVE_INFINITY
let y = Number . POSITIVE_INFINITY
let z = x + y
console . log ( z )0undefinedNaNTypeError負_infinity和usation_infinity是JavaScript中數字對象的屬性,它代表了負相關和正無窮大的數學概念。
當您添加number.negation_infinity and number.posisitive_infinity時,結果是NAN。
將正無限的無限值添加到負無限值並不會導致有意義的數值。
因此,在這種情況下,Z將是Nan。
請注意,該代碼不會拋出TypeError,因為JavaScript能夠執行number.negation_infinity和number.posisity_infinity之間的添加操作。
console . log ( 'BG Web Agency' === NaN , isNaN ( 'BG Web Agency' ) )true, truefalse, truetrue, falsefalse, false使用=== NaN檢查值是否為一個數字是行不通的。
在JavaScript中, NaN (不是一個數字)是代表無效數字的特殊值。
NAN不等於任何內容,包括本身,因此"BG Web Agency" === NaN總是會返回false 。
要檢查一個值是否是JavaScript中的數字,您可以使用isNaN()函數。如果傳遞給它的參數是NaN ,或者不能將其轉換為數字,則此函數將返回true
console . log ( isFinite ( Infinity ) , isNaN ( Infinity ) )false, falsefalse, truetrue, falsefalse, false isFinite()函數用於確定給定值是否為有限數。
如果值為NAN,INFINITY或-INFINITY,則返回false,如果值為有限數字,則返回false。
因此,在此示例中, isFinite(Infinity)將返回False,因為Infinity不是有限的數字。
另一方面,使用isnan()函數來確定給定值是否不是數字(NAN)。
如果值為NAN,則返回true,如果值為數字或任何其他數據類型,則false。
因此,在此示例中, isNaN(Infinity)也將返回False,因為Infinity不是Nan。
isFinite ,當您要驗證一個數字是isNaN時
const user = {
name : 'John' ,
age : 30 ,
getName : ( ) => {
return this . name
} ,
getAge : function ( ) {
return this . age
} ,
}
const getName = user . getName
const getAge = user . getAge
console . log ( getName ( ) )
console . log ( getAge ( ) ) getName箭頭函數使用this關鍵字來參考對象的名稱屬性,但是由於箭頭函數具有詞彙性this ,因此箭頭函數中this關鍵字的值將是瀏覽器中的window ,或node.js中的global 。
由於global對像上沒有名稱屬性,因此該函數返回undefined 。
getAge函數使用常規函數表達式,並使用this關鍵字正確地指user對象的年齡屬性。
但是,當將getAge分配到getAge變量時,它會失去對user對象的引用,因此,當使用getAge()調用函數時,這將再次引用全局對象,並且由於全局對像上沒有age屬性,因此該函數返回不確定。
for ( var i = 0 ; i < 3 ; i ++ ) {
setTimeout ( function ( ) {
console . log ( i )
} , 0 )
}閉合是一個函數,即使外部函數返回,也可以在其外部範圍中保留對變量的訪問。
在此示例中,答案是B,因為Settimeout函數是異步的,並且不會立即執行。
到執行傳遞給settimeout的回調函數時,循環已經完成,i變量的值為3。
因此,回調函數中的每個調用console.log(i)都將打印3。
為了解決此問題並打印0、1、2,我們可以使用IIFE(立即調用函數表達式)為環路的每個迭代創建一個新的範圍。
這將在每個IIFE內部創建一個新的變量J,並在循環的該迭代中使用其當前值的副本。
當執行將回調函數傳遞給SettiMeout時,它可以訪問其關閉中的J變量,該循環的每次迭代的預期值為0、1或2。
function add ( x ) {
return function ( y ) {
if ( y !== undefined ) {
x += y
return arguments . callee
} else {
return x
}
}
}
console . log ( add ( 1 ) ( 2 ) ( 3 ) ( ) )正確的答案是A。代碼定義了一個添加函數,該函數採用單個參數x並返回另一個參數y的函數。
此內部函數檢查是否定義y。如果定義了它,它將y添加到x,並使用gragments.callee屬性返回對自身的引用,該屬性允許使用下一個參數遞歸調用該函數。
如果未定義y,它將返回x的當前值。
然後,代碼調用添加(1)(2)(3)()。首先將其添加為1個參數添加(1),該參數返回一個參數y的函數。
然後,它將此函數稱為2作為其參數,該函數增加了2比1並返回對該函數的引用。
最後,它將此函數稱為3為參數,該函數增加了3至3,並返回對該功能的引用。
由於在最後一個呼叫中沒有參數,因此它返回X的當前值,即6。
該代碼演示了在JavaScript中進行咖哩的更複雜的示例,其中咖哩函數返回對自身的引用,從而使其與下一個參數一起遞歸地稱為。
function multiply ( x ) {
return function ( y ) {
return x * y
}
}
const double = multiply ( 2 )
console . log ( double ( 5 ) )正確的答案是B。代碼定義了一個乘法函數,該功能採用單個參數x並返回另一個參數y的函數。此內部函數乘以x和y,並返回結果。
然後,該代碼通過將乘數稱為2來創建一個新函數。現在,雙函數是一個咖哩函數,可以用單個參數調用以使其值加倍。
最後,該代碼以5為duble將其稱為其參數,這將導致10登錄到控制台。
該代碼演示了JavaScript中咖哩的概念,其中一個函數返回可以通過某些參數部分應用的另一個函數。
關於JavaScript中迭代器的next()方法,以下哪個語句是正確的?
正確的答案是A。
在JavaScript中,一個峰值是一個定義序列並可以使用循環迭代的對象。
迭代器是一個知道如何一次訪問一個元素的對象。
一個峰值對象具有帶有鍵Symbol.iterator方法,該方法返回迭代對象。
迭代器對象具有next()方法,該方法返回一個具有兩個屬性的對象: value ,這是序列中的下一個元素,並且done ,這是一個布爾值,指示迭代器是否已達到序列的末尾。
與大型數據集合作或實現自定義數據結構時,迭代量通常在許多實時應用程序中使用
function * counter ( ) {
let i = 0
while ( true ) {
yield i ++
}
}
const gen = counter ( )
console . log ( gen . next ( ) . value )
console . log ( gen . next ( ) . value )
console . log ( gen . next ( ) . value )上述代碼片段輸出什麼?
正確的答案是D。
counter函數是創建無限循環的生成器函數,該循環產生i的增量值。
gen變量設置為發電機函數,每個呼叫to gen.next()返回一個對象,其中值設置為下一個產量的值。
然後, console.log語句打印gen.next()返回的值。
生成器函數是一種特殊的函數,可用於通過一系列值來控制迭代。
與傳統功能不同,生成器功能使您可以暫停並恢復其執行,並隨著時間的推移產生多個值。
以下哪些情況可能會導致JavaScript中的內存洩漏?
當兩個或多個對象相互引用時,就會發生循環引用,從而創建一個循環,以防止對象收集垃圾。
如果不再需要對象,但由於圓形參考,這可能會導致內存洩漏。
選項A,C和D通常不會在JavaScript中導致內存洩漏。
垃圾收集是自動釋放程序不再使用的內存的過程。
在JavaScript中,商標和掃描算法通常用於垃圾收集。
該算法通過首先標記程序中仍在引用的內存中的所有對象來起作用,然後掃描並釋放任何未標記為使用中的內存。
function getData ( ) {
return new Promise ( ( resolve , reject ) => {
setTimeout ( ( ) => {
resolve ( 'Data retrieved successfully' )
} , 1000 )
} )
}
async function main ( ) {
try {
const data = await getData ( )
console . log ( data )
throw new Error ( 'Something went wrong' )
} catch ( err ) {
console . log ( 'Caught an error:' , err . message )
return 'Error occurred'
} finally {
console . log ( 'Finally block executed.' )
return 'Finally block value'
}
}
; ( async ( ) => {
console . log ( await main ( ) )
} ) ( )上述代碼片段輸出什麼?
執行代碼後,稱為Main()函數,這是一個異步函數,使用等待從getData()函數獲取數據。
檢索數據後, console.log(data)語句將“成功檢索”到控制台。
之後, throw new Error("Something went wrong")語句會引發錯誤。
catch塊捕獲錯誤,並記錄"Caught an error: Something went wrong" ,然後返回字符串"Error occurred" 。
最後,最後執行塊,並記錄"Finally block executed."到控制台,然後返回字符串"Finally block value" 。
當調用main()函數時,它會返回承諾,因為它是異步函數。由於finally塊還返回一個值,因此該值將是承諾的最終解析值。
因此,當調用console.log(main())時, "Finally block executed."並且"Finally block value"將記錄到控制台。
嘗試,捕獲,最後是JavaScript中用於處理運行時錯誤的關鍵字。
const arr = [ 1 , 2 , 3 , 4 , 5 ] ;
let sum = 0 ;
for ( let num of arr ) {
sum += num ;
if ( sum >= 6 ) break ;
}
console . log ( sum ) ;
const arr2 = [ 1 , 2 , 3 , 4 , 5 ] ;
let sum2 = 0 ;
arr . forEach ( ( num ) => {
sum2 += num ;
if ( sum2 >= 6 ) break ;
} ) ;
console . log ( sum2 ) ;上述代碼片段輸出什麼?
因為break語句在傳遞給forEach回調函數內無效。
forEach不支持使用break語句的早期終止。因此,拋出了一個錯誤: "Uncaught SyntaxError: Illegal break statement".
如果是循環,則允許break聲明。
要解決該問題,請從foreach中刪除break語句,它應該起作用。
通常, for of for in forEach
let arr = [ 1 , 2 , 3 , 4 ]
let result = arr . push ( 5 )
console . log ( 'result: ' , result , 'arr: ' , arr )上述代碼片段輸出什麼?
JavaScript中的array.push()方法將一個或多個元素添加到數組末尾,並返回數組的新長度。
在給定代碼中, arr是一個具有值[1, 2, 3, 4]數組。 push()方法與參數5一起調用,該方法將5添加到arr數組的末端。
push()方法在添加元素後返回陣列的新長度。在這種情況下,新的ARR長度將為5,因為5添加到數組的末端。
let arr = [ 3 , 5 , 7 , 9 ]
let result = arr . unshift ( 1 , 2 )
console . log ( 'result: ' , result , 'arr: ' , arr )上述代碼片段輸出什麼?
JavaScript中的array.unshift()方法在數組的開頭添加一個或多個元素,並返回數組的新長度。
在給定代碼中, arr是一個具有值[3, 5, 7, 9]數組。 unshift()方法與參數1和2一起調用,該方法將1和2添加到arr數組的開頭。
unshift()方法在添加元素後返回陣列的新長度。在這種情況下,新的arr的新長度將為6,因為1和2添加到數組的開頭,將現有元素轉移到右側。
const myArray = [ 1 , 2 , 3 , 4 , 5 ]
const poppedValue = myArray . pop ( )
console . log ( poppedValue )上述代碼片段輸出什麼?
JavaScript中的Array.pop()方法從數組中刪除了最後一個元素,並返回該元素。
在這種情況下, myArray是一個帶有元素[1, 2, 3, 4, 5]數組,稱為myArray.pop() ,它從數組中刪除了元素5並返回。
const arr = [ 10 , 20 , 30 , 40 , 50 ]
const removedElement = arr . shift ( )
console . log ( 'removedElement: ' , removedElement , 'arr: ' , arr )上述代碼片段輸出什麼?
Array.shift()方法從arr數組(即10 )中刪除了第一個元素,並將其返回。然後,所得的arr陣列將為[20, 30, 40, 50] 。
因此,選項A是正確的答案,因為它反映了removedElement的正確值,並且調用了Array.shift()後的arr的更新狀態。選項B是不正確的,因為它指出removedElement將為50,這是不正確的。選項C也不正確,因為它聲明arr保持不變,這是不准確的。選項D有些混亂,因為它指出Array.shift()返回數組,這是不正確的。
let arr = [ 1 , 2 , 3 , 4 , 5 ]
let removed = arr . splice ( 1 , 2 , 'a' , 'b' )
console . log ( 'removed:' , removed , 'arr: ' , arr )上述代碼片段輸出什麼?
Array.splice()方法用於通過添加,刪除或替換元素來修改數組。
在這種情況下,代碼片段使用arr.splice(1, 2, 'a', 'b') ,該碼從索引1(刪除2個元素)開始,並將元素a和b插入其位置。將刪除的元素(即2和3)返回並分配給已刪除的變量。執行後,刪除將為[2, 3] , arr將為[1, 'a', 'b', 4, 5] 。選件C不正確,因為它包括刪除陣列中的插入元素,這是不准確的。選項D也是不正確的,因為它提到了從數組中刪除的不正確元素。
const fruits = [ 'apple' , 'banana' , 'orange' , 'grape' , 'apple' , 'kiwi' ]
const index = fruits . indexOf ( 'orange' )
const lastIndex = fruits . lastIndexOf ( 'apple' )
const result = fruits . includes ( 'grape' )
console . log ( 'index: ' , index , 'lastIndex: ' , lastIndex , 'result: ' , result )上述代碼片段輸出什麼?
Array.indexOf()方法搜索陣列水果中指定值的第一次出現的索引。在這種情況下,在索引2處發現“橙色”,因此index為2。
Array.lastIndexOf()方法搜索陣列水果中指定值的最後一次出現的索引。在這種情況下,“ Apple”在數組中出現兩次,其最後一次發生在索引4,因此lastIndex將為4。
另一方面, Array.includes()方法檢查陣列水果中指定的值是否存在“葡萄”,並且由於數組中存在“葡萄”,因此result將是正確的。
function isDivisibleBy7 ( num ) {
return num % 7 == 0
}
const nums = [ 28 , 7 , 3 , 29 , 15 , 1 , 2 , 23 ]
const filterResult = nums . filter ( isDivisibleBy7 )
const findResult = nums . find ( num => num < 10 )
const findIndexResult = nums . findIndex ( num => num / 2 == 14 )
console . log (
'filterResult:' ,
filterResult ,
'findResult:' ,
findResult ,
'findIndexResult:' ,
findIndexResult ,
)上述代碼片段輸出什麼?
Array.filter()方法返回一個數組,其中包含傳遞給它的函數的所有元素返回true。在這種情況下, isDivisibleBy7函數對於7。在數字中排除的任何數字返回true。在nums陣列中,7和28在7中被7分開,因此nums.filter(isDivisibleBy7)返回[28,7]。
Array.find()方法返回傳遞給它的函數返回true的數組中的第一個元素。在這種情況下,傳遞給它的函數對於小於10的任何數字返回true。 nums中有多個小於10的數字,但是由於Array.find()僅返回第一個是正確的, nums.find((num) => num < 10)返回7。
Array.findIndex()方法類似於Array.find()方法,但返回傳遞函數傳遞給它的數組中的第一個元素的索引,而不是元素本身。在這種情況下,傳遞給它的函數返回為28,因為28 /2 ==14。28在nums中,在索引0中,因此nums.find((num) => num / 2 == 14)返回0。
const numbers = [ 1 , 2 , 3 , 4 , 5 ]
const doubledNumbers = numbers . map ( num => num * 2 )
console . log ( doubledNumbers )上述代碼片段輸出什麼?
JavaScript中的Array.map()方法通過將提供的函數應用於原始數組的每個元素來創建新數組。
在這種情況下,提供的函數num => num * 2將數字數組中的每個數字乘以2,從而導致新數組[2, 4, 6, 8, 10] 。
const numbers = [ 1 , 2 , 3 , 4 , 5 ]
const sum = numbers . reduce ( ( acc , val ) => acc + val )
console . log ( sum )上述代碼片段輸出什麼?
Array.reduce()使用一個數組,並通過重複將函數應用於每個元素並跟踪累積結果,將其“減少”為單個值。它通常用於任務,例如總結數字數組,找到最大值或將一系列字符串串聯成一個字符串。
在這種情況下,reald()方法採用為數組的每個元素執行的回調函數。回調函數分別代表累加器和數組的當前值,採用兩個參數, acc和val 。
在回調函數內部,數組的當前值添加到累加器中,並返回結果。 reduce()方法通過每次迭代更新累加器的值,直到在數組的所有元素上進行迭代為止。
最後, reduce()方法返回累加器的最終值,即數組中所有數字的總和為15。
const arr = [ 1 , 2 , 3 , 4 ]
const result = arr . reduceRight ( ( acc , curr ) => acc + curr )
console . log ( result )上述代碼片段輸出什麼?
reduceRight()方法類似於reduce()方法,只是它開始將數組從最右邊的元素減少到最左的元素。 reduceRight()方法適用於累加器和數組的每個值(從右到左),以將其降低到單個值。
在給定的代碼段中, arr數組包含值[1, 2, 3, 4] 。在此數組上調用了reduceRight()方法,並帶有回調函數,該回調函數將累加器acc與當前元素curr添加。
在第一次迭代中, curr值將為4 ,並且ACC值將undefined ,因為沒有提供初始值。因此,第一次迭代的結果將為4 。
在第二個迭代中, curr值將為3 , acc值將是上一個迭代的結果,即4 。因此,第二次迭代的結果將為7 。
在第三個迭代中, curr值將為2 , acc值將是上一個迭代的結果,即7 。因此,第三次迭代的結果將為9 。
在第四次也是最後一次迭代中, curr值將為1 , acc值將是上一個迭代的結果,即9 。因此,第四次迭代的結果將為10 。
因此,代碼的最終輸出將為10 。因此,正確的選項是A。
const arr = [ 'Centauri' , 3.14159 , 'canine' , 11235 , undefined ]
const result = arr . sort ( )
console . log ( result )上述代碼片段輸出什麼?
默認情況下, sort()方法按字符對元素進行分類,因此11235在3.14159之前出現在3.14159之前,因為1在3之前。
單詞和字母由ASCII代碼按字母順序排序,因此“ Centauri”以大寫C(ASCII代碼67)的形式開頭,然後以“犬”為開頭,以小寫C(ASCII代碼99)開始。
未定義的元素總是排序到陣列的末端。
因此,代碼的最終輸出將為[11235,3.14159,'centauri','犬',不確定],這是選項D。
let numbers = [ 1 , 2 , 3 , undefined , 6 , 7 , 8 , 9 ]
let [ a , , b , c = 2 , ... rest ] = numbers
console . log ( a , b , c , rest )上述代碼片段輸出什麼?
隨著陣列破壞,可以將某些值從數組中解放為單個變量。我們在左側( a, b, c, rest )中創建的值對應於我們在右側( numbers )中分配的數組的值和順序。
變量a對應於數組的第一個元素,即1 。
由於我們沒有為下一個值2指定變量,因此在評估中未考慮該值並跳過。
變量b對應於數組的第三個元素,即3 。
如果數組中的元素undefined ,則可以為變量設置默認值。由於數組中的第四個元素是undefined ,因此變量c具有默認值2 。
使用傳播運算符( ... ),我們可以將數組的剩餘值分配給變量。由於值[ 6, 7, 8, 9 ]是數組的其餘值,因此它們被分配給變量rest 。
因此,最終結果是: 1 3 2 [ 6, 7, 8, 9 ] ,這是選項B。
const date1 = new Date ( )
const date2 = new Date ( '1995-12-17T05:10:00' )
const date3 = new Date ( '1995-10-15T08:12:15+02:00' )
console . log ( date1 , '' , date2 , '' , date3 )上述代碼片段輸出什麼?
new Date()將返回當前日期和時間,然後以“ Yyyy-Mm-Ddthh:MM:MM:SS.SSSZ”格式返回兩個指定的日期,其中“ Z”代表UTC時區偏移。
YYYY-MM-DDTHH:mm:ss.sssZ是一種用於表示ISO 8601標準中日期和時間的格式。它由以下組成部分組成:
YYYY :四位數的年份(0000至9999),或以 +或 - 接著六位數的擴展年份。擴大年份需要的標誌是必需的。 -000000明確不允許作為有效的一年。MM :兩個數月(01 = 1月,02 = 2月,依此類推)。它默認為01。DD :一個月的兩位數(01至31)T :一個指示時間組件開始的分離器HH :一天中的兩位數以24小時格式(00至23)。作為特殊情況,允許24:00:00,並在第二天初被解釋為午夜。默認為00。mm :小時的兩位分(00至59)。默認為00。ss :分鐘的兩位數(00至59)。默認為00。.sss :毫秒組件(000至999)。默認為000。Z :一個後綴表示時間在UTC(協調的通用時間),沒有偏移。它可以是字面字符z(指示UTC),或者 +或 - 後跟HH:mm,距UTC的數小時和幾分鐘的偏移。 const date = new Date ( 'Mart 15, 1975 23:15:30' )
date . setMinutes ( 10 )
date . setUTCDate ( 5 )
console . log (
'Minutes:' + date . getMinutes ( ) + ',' ,
'' ,
'Year:' + date . getFullYear ( ) + ',' ,
'' ,
'UTCDate:' + date . getUTCDate ( ) ,
)上述代碼片段輸出什麼?
提供的代碼創建了一個日期對象,並以“ 1975年3月15日23:15:30”的日期和時間初始化。
然後,它分別使用setMinutes()和setUTCDate()方法修改日期對象的分鐘和UTC日期。
最後,它使用console.log()記錄了分鐘,年和UTC日期的更新值。
在使用setMinutes(10)將分鐘修改為10之後, getMinutes()方法將返回10的更新值10。
在使用setUTCDate(5)將UTC日期修改為5之後, getUTCDate()方法將返回5的更新值。
getFullYear()方法返回未改變的一年,即1975年。
const date1 = new Date ( '2023-5-1' )
const next_us_election = new Date ( '2024-11-5' )
const difference_in_time = next_us_election . getTime ( ) - date1 . getTime ( )
const difference_in_days = difference_in_time / ( 1000 * 3600 * 24 )
console . log ( parseInt ( difference_in_days , 10 ) + ' Days' )上述代碼片段輸出什麼?
該代碼計算“ 2023-5-1”日期與下一個美國選舉日期“ 2024-11-5”之間的天數。它使用Date對象創建兩個日期: date1代表5月1日,2023年, next_us_election代表2024年11月5日。
getTime()方法用於在每個日期以毫秒為單位獲得時間值。通過從next_us_election中減去date1的時間值,我們獲得了毫秒的時間差。
為了將毫秒從毫秒轉換為天數,我們將其除以一天內的毫秒數(1000 _ 3600 _ 24)。結果存儲在變量difference_in_days中。
最後, parseInt()函數用於將差異_in_days值轉換為整數,結果將與“ days”字符串一起記錄到控制台。輸出將為“ 554天”。
let person = {
name : 'John' ,
age : 30 ,
hobbies : [ 'reading' , 'traveling' , 'cooking' ] ,
address : {
street : '123 Main St' ,
city : 'New York' ,
state : 'NY' ,
} ,
sayHello : function ( ) {
console . log ( 'Hello, my name is ' + this . name )
} ,
}
console . log ( person . name )
console . log ( person . hobbies [ 1 ] )
console . log ( person . address . city )
person . sayHello ( )上述代碼片段輸出什麼?
該代碼定義了一個具有屬性的對象person ,例如name , age , hobbies和address ,以及一種方法sayHello 。
console.log()語句打印name的值, hobbies數組的第二個要素(即“旅行”)以及address對像中city屬性的價值(即“紐約”)。
最後,使用點符號將sayHello進行調用,該person將字符串輸出“ Hello,我的名字是John”到控制台。
function User ( username ) {
this . username = username
this . updateUsername = newName => {
this . username = newName
}
}
const user1 = new User ( 'kirandash' )
const user2 = new User ( 'bgwebagency' )
user1 . updateUsername ( 'kirandash-website' )
user2 . updateUsername ( 'bgwebagency-app' )
console . log ( user1 . username , user2 . username )上述代碼片段輸出什麼?
該代碼定義了使用username屬性和updateUsername方法創建user對象的構造函數User 。 user1兩個user對象user2使用初始用戶名“ kirandash”和“ bgwebecency”創建。
在user1和user2對像上都調用了updateUsername方法以更新其用戶名。 user1的用戶名已更新為“ Kirandash-Website”,並且user2的用戶名更新為“ bgwebagencency-app”。
最後,該代碼記錄了user1.username和user2.username的串聯,這將導致輸出“ kirandash-website bgwebagencency-app”。
function greet ( name ) {
console . log ( `Hello, ${ name } ! Welcome to ${ this . location } .` )
}
const person = {
location : 'New York' ,
}
greet . call ( person , 'John' )
greet . apply ( person , [ 'Alex' ] )
const greetPerson = greet . bind ( person )
greetPerson ( 'Thomas' )上述代碼片段輸出什麼?
call函數用於person對像作為上下文( this值)和'John'作為參數調用greet函數。
apply函數用於將greet person作為上下文( this值的值)和數組['Alex']作為參數調用。
The bind function is used to create a new function greetPerson with the person object as the bound context (the value of this ).
In summary, the code demonstrates how call , apply , and bind can be used to invoke a function with a specific context and arguments
class Animal {
constructor ( name ) {
this . name = name
}
static makeSound ( ) {
console . log ( 'Generic animal sound' )
}
sayName ( ) {
console . log ( `My name is ${ this . name } ` )
}
}
const a1 = new Animal ( 'Lion' )
const a2 = new Animal ( 'Time' )
Animal . makeSound ( )
a1 . makeSound ( )
a2 . makeSound ( )What does the above code snippet output?
The static method makeSound() is defined on the Animal class, and is accessible directly through the class itself, ie, Animal.makeSound() . This will output "Generic animal sound" to the console.
However, when we try to call makeSound() on an instance of the Animal class (a1.makeSound() and a2.makeSound()) , we get a TypeError, because static methods can only be accessed through the class itself and not through its instances.
function Animal ( name ) {
this . name = name
}
Animal . prototype . eat = function ( ) {
console . log ( this . name + ' is eating.' )
}
function Dog ( name ) {
Animal . call ( this , name )
}
Dog . prototype = Object . create ( Animal . prototype )
Dog . prototype . constructor = Dog
Dog . prototype . bark = function ( ) {
console . log ( this . name + ' is barking.' )
}
function CustomArray ( ) {
Array . call ( this )
}
CustomArray . prototype = Object . create ( Array . prototype )
CustomArray . prototype . constructor = CustomArray
CustomArray . prototype . sum = function ( ) {
return this . reduce ( ( acc , val ) => acc + val , 0 )
}
var dog = new Dog ( 'Buddy' )
dog . eat ( )
dog . bark ( )
var numbers = new CustomArray ( )
numbers . push ( 1 , 2 , 3 , 4 , 5 )
console . log ( numbers . sum ( ) )What will be the output of the following code
Explanation: In this example, we have a base class called Animal that defines a constructor and an eat() method. The subclass Dog extends the Animal class and adds its own constructor, bark() method, and a specific property breed .
Furthermore, we extend the built-in Array class using the class syntax to create a CustomArray class. The CustomArray class adds a custom method called sum() that calculates the sum of the array elements.
In the usage section, we create an instance of Dog named dog with the name "Buddy" . We can call the inherited eat() method from the Animal class, the bark() method defined in the Dog class.
Additionally, we create an instance of CustomArray called numbers and add some numbers to it. We can call the custom sum() method, which is added to the built-in Array class through subclassing.
This example showcases inheritance, subclassing, and extending a built-in class in JavaScript, illustrating how classes can be extended and customized to add additional functionality.
const person = {
name : 'John' ,
age : 30 ,
city : 'New York' ,
}
const { name , age , city } = person
console . log ( name )
console . log ( age )
console . log ( city )What will be the output of the following code
In the code above, we have an object literal called person with properties name , age , and city . We then use object destructuring to extract those properties into separate variables ( name , age , and city ). After destructuring, we can use these variables to access the corresponding values from the object.
Consider the following code snippet:
// module.mjs
export const PI = 3.14159
export function calculateArea ( radius ) {
return PI * radius * radius
}
export default function calculateCircumference ( radius ) {
return 2 * PI * radius
}
// script.mjs
import calculateCircumference , { PI , calculateArea } from './module.mjs'
console . log ( PI ) // Output: ________
console . log ( calculateArea ( 5 ) ) // Output: ________
console . log ( calculateCircumference ( 5 ) ) // Output: ________What will be the output of the console.log statements in the code above?
選項:
3.14159 , 78.53975 , 31.41593.14159 , 78.53975 , 62.83183.14159 , 78.53975 , NaN3.14159 , NaN , 62.8318 The module.js file exports three entities:
PI is a named export, exported using the export keyword.calculateArea is a named export, exported using the export keyword.calculateCircumference is the default export, exported using the export default syntax. In the main.js file, we import PI and calculateArea as named exports using the destructuring assignment syntax. We also import calculateCircumference as the default export. The import statements reference the module.js file using the relative file path ./module.js .
The outputs of the console.log statements will be:
console.log(PI) will output 3.14159 since we imported the named export PI .console.log(calculateArea(5)) will output 78.53975 since we imported the named export calculateArea and called the function with a radius of 5.console.log(calculateCircumference(5)) will output 62.8318 since we imported the default export calculateCircumference and called the function with a radius of 5. Consider the following code snippet:
// foo.js
function foo ( ) {
console . log ( `Foo` )
}
export { foo } What is the correct Syntax to import the function foo ?
選項:
import foo from "./foo"import foo as FooFunction from "./foo"import { foo } from "./foo"import { foo } from "./bar" Named exports are imported into different files with braces and must be imported with the name of the object, function or variable that was exported. In this example, a function with the name foo is exported from the file foo.js . Accordingly, the correct expression is: import { foo } from "./foo" .
In JavaScript, when importing a default export from a module, which syntax correctly assigns an alias "myAlias" to the default import?
Explanation: Both option B and C are valid syntaxes for importing a default export from a module and assigning it an alias. The difference between the two syntaxes is that option B does not use the { default as myAlias } syntax. This means that the default export will be imported under the name myAlias, rather than the name default.
Here is an example of how to use the option B syntax:{import myAlias from 'module';},This will import the default export from the module module and assign it the name myAlias. You can then use the myAlias variable to access the default export from the module module. Here is an example of how to use the option C syntax:{import { default as myAlias } from 'module';},This will import the default export from the module module and assign it the alias myAlias. You can then use the myAlias alias to access the default export from the module module.
The choice of which syntax to use is up to you. The option B syntax is simpler, but it can lead to collisions if there is already a variable named myAlias in the current scope. The option C syntax is more verbose, but it avoids collisions.
Which method is used to convert a JavaScript object to a JSON string while preserving data types like Dates and RegEx?
JSON.stringify()JSON.stringify() with a custom replacer functionJSON.toTypedString()JSON.stringify()JSON.stringify() with a custom replacer function. Explanation: The JSON.stringify() method can be used to convert a JavaScript object to a JSON string. However, by default, it will not preserve data types like Dates and RegEx . To preserve these data types, you can use a custom replacer function. The replacer function takes an object as input and returns a new object with the modified values.
The code below would show you how to use a custom replacer function to preserve data types:
function replacer ( key , value ) {
if ( typeof value === 'Date' ) {
return value . toJSON ( )
} else if ( typeof value === 'RegExp' ) {
return value . toString ( )
} else {
return value
}
}
const object = {
date : new Date ( ) ,
regex : / some regex / ,
}
const jsonString = JSON . stringify ( object , replacer )