フロントエンド/ウェブコーディングインタビューのためにJavaScriptを学ぶ楽しい方法。すべての質問はここでテキストで回答され、YouTubeチャンネルにもビデオがあります。クリックします
ソーシャルプラットフォームでお気軽にご連絡ください! ?
不和|| Instagram || Twitter || Tiktok ||ブログ|| Facebook
サポート
このプロジェクトに出演し、他の人と共有してサポートを示してください。将来のプロジェクトとチュートリアルの最新情報については、私にフォローしてください!
言語の基本 - 配列 - 日付と時刻 - オブジェクト指向JavaScript-モジュール - その他
console . log ( new Date ( 2023 , 1 , 31 ) )Tue Jan 31 2024Tue Jan 31 2023Fri Mar 03 2023ErrorJavaScriptでは、日付オブジェクトを使用して日付を作成しながら、月は0ベースです。つまり、0は1月で、1は2月の場合です。
したがって、この場合、JavaScriptに存在しない2023年2月31日の日付を設定するよう求めています。
しかし、エラーを投げる代わりに、JavaScriptは3月である翌月にそれをオーバーフローします。
また、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オブジェクトにバインドされていません。
したがって、UpdateSusername関数内のthisキーワードは、 userオブジェクトを参照するのではなく、グローバルスコープを参照しています。
この問題を修正するには、矢印関数を通常の関数に変更する必要があります。
const len1 = 'kiran' . length
const len2 = '?' . length
console . log ( len1 , len2 )5, 25, 15, undefined5, SyntaxErrorJavaScriptでは、文字列長プロパティは、予想される文字の数ではなく、バイト数を返します。
絵文字は、2バイトでエンコードされるユニコード文字です。したがって、この質問の答えは2です。
文字列には各文字が1バイトであるため、 kiranの文字列の長さは5返します。
console . log ( undefined == null , undefined === null )true, truetrue, falsefalse, falsefalse, trueまず、等しいオペレーターと厳格なオペレーターの違いを説明させてください。
等しい演算子は、両方の値が等しいかどうかのみをチェックします。厳密な等しい演算子は、値とタイプの両方が等しいかどうかをチェックします。
したがって、このコードでは、 undefinedとnullの両方が同じ値を空にするため、最初のステートメントはundefined == nullがtrueを返します。
しかし、2番目のステートメントはundefined === nullがfalseを返します。 typeof undefined undefinedであるため、 typeof nullはobjectです。
nullが基本的に原始的なデータ型である場合、 typeof null objectであるのか疑問に思うかもしれません。これは基本的に、最初からJavaScriptの間違いです。
さて、もう1つのヒント: undefinedの代わりに変数使用nullの空の値を設定する場合。 undefinedは主に変数に値が割り当てられていないかどうかを確認するために使用されるためです。
function getFruits ( x , ... multi , y ) {
console . log ( x , y , multi ) ;
}
getFruits ( "?" , "?" , "?" , "?" , "?" )? ? ["?", "?", "?"]SyntaxErrorRESTオペレーターは、ES6機能の一部として追加されました。
関数に渡されたすべての引数を取り、それを配列に入れます。
複数の引数が関数に渡される場合、休憩オペレーターは最後に来なければなりません。そのため、このコードスニペットがエラーをスローします。
この問題を修正するには、残りのオペレーターを最後まで移動してください。その後、機能するはずです。
let x = Number . NEGATIVE_INFINITY
let y = Number . POSITIVE_INFINITY
let z = x + y
console . log ( z )0undefinedNaNTypeErrorNegial_infinityとPosute_infinityは、負の無限と正の無限の数学的概念を表すJavaScriptの数値オブジェクトのプロパティです。
number.negative_infinityとnumber.positive_infinityを追加すると、結果はnanになります。
否定的な無限値に正の無限値を追加しても、意味のある数値値が得られません。
したがって、この場合、zはナンになります。
JavaScriptはnumber.negative_infinityとnumber.positive_infinityの間の追加操作を実行できるため、コードはtypeRrorをスローしないことに注意してください。
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の場合、値が有限数である場合はTrueの場合はfalsを返します。
したがって、この例では、 isFinite(Infinity) Infinityが有限数ではないためFalseを返します。
一方、ISNAN()関数は、特定の値が数(NAN)ではないかどうかを判断するために使用されます。
値がNANの場合はtrue、値が数値または他のデータ型である場合はfalseを返します。
したがって、この例では、 isNaN(Infinity)もInfinityがNANではないためFalseを返します。
したがって、数値が有限であるかどうかを検証する場合は、 isNaN関数の代わりに常にisFinite関数を使用します
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 Arrow関数はthisキーワードを使用してオブジェクトの名前プロパティを参照しますが、矢印関数にはthisバインディングが語彙的であるため、矢印関数内のthisキーワードの値は、ブラウザのwindow 、またはnode.jsのglobalであるグローバルオブジェクトになります。
globalオブジェクトに名前のプロパティがないため、関数はundefined 。
getAge関数は通常の関数式を使用し、 thisキーワードを使用してuserオブジェクトの年齢特性を正しく指します。
しかし、 getAge getAge変数に割り当てられると、 userオブジェクトへの参照が失われるため、関数がgetAge()を使用して呼び出されると、これは再びグローバルオブジェクトを参照し、グローバルオブジェクトに年齢特性がないため、関数は未定義です。
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が作成され、ループの反復でのIの現在の値の独自のコピーが作成されます。
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に追加し、arguments.calleeプロパティを使用してそれ自体への参照を返します。これにより、次の引数で関数を再帰的に呼び出すことができます。
yが定義されていない場合、xの現在の値を返します。
次に、コードは(1)(2)(3)()を呼び出します。これは、最初に(1)が引数として(1)を呼び出します。これは、単一の引数yを取る関数を返します。
次に、この関数を2から1を引数と呼び、2対1を追加し、関数への参照を返します。
最後に、この関数を3でその引数と呼び、3〜3を追加し、関数への参照を返します。
最後の呼び出しで引数は渡されないため、xの現在の値は6です。
このコードは、JavaScriptでのカレーのより複雑な例を示しています。ここでは、Curried関数がそれ自体への参照を返し、次の引数で再帰的に呼ばれるようにします。
function multiply ( x ) {
return function ( y ) {
return x * y
}
}
const double = multiply ( 2 )
console . log ( double ( 5 ) )正解はBです。コードは、単一の引数xを取る複数の関数を定義し、単一の引数yを取る別の関数を返します。この内部関数はxとyを掛け、結果を返します。
次に、コードは引数としてMultiplyと2を呼び出すことにより、新しい関数を2倍に作成します。二重関数は、その値を2倍にするために単一の引数で呼び出すことができる通信機能になりました。
最後に、コードは引数として5でダブルを呼び出し、その結果、10がコンソールにログに記録されます。
このコードは、JavaScriptでのカレーの概念を示しています。このコードでは、関数がいくつかの引数で部分的に適用できる別の関数を返します。
JavaScriptのIteratorのnext()メソッドについては、次のステートメントのどれが当てはまりますか?
正解はAです。
JavaScriptでは、反復可能なものは、シーケンスを定義し、ループを使用して反復できるオブジェクトです。
イテレーターは、一度に反復可能な要素の要素にアクセスする方法を知っているオブジェクトです。
反復可能なオブジェクトには、キーSymbol.iteratorを使用したメソッドがあり、Iteratorオブジェクトを返します。
Iteratorオブジェクトには、 next()メソッドがあります。これは、2つのプロパティを持つオブジェクトを返します。これ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変数はジェネレーター関数に設定され、 gen.next()への各呼び出しは、値プロパティが次の値に設定されたオブジェクトを返します。
console.logステートメントは、 gen.next()によって返された値を印刷します。
ジェネレーター関数は、一連の値に対する反復を制御するために使用できる特別なタイプの関数です。
従来の関数とは異なり、ジェネレーター関数を使用すると、実行を一時停止して再開し、時間の経過とともに複数の値を生成できます。
次のシナリオのうち、JavaScriptのメモリリークを潜在的に引き起こす可能性のあるシナリオはどれですか?
循環参照は、2つ以上のオブジェクトが互いに参照しているときに発生し、オブジェクトが収集されるのを防ぐループを作成します。
これにより、オブジェクトが不要になったが、円形の参照のために解放できない場合、メモリリークが発生する可能性があります。
オプション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 Statementを使用した早期終了をサポートしていません。したがって、エラーがスローされます: "Uncaught SyntaxError: Illegal break statement".
ループの場合、 breakステートメントが許可されます。
問題を修正するには、Foreachからbreak Statementを削除すると機能するはずです。
一般的に、 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()メソッドは、配列の最後に1つ以上の要素を追加し、配列の新しい長さを返します。
指定されたコードでは、 arrは値[1, 2, 3, 4]を持つ配列です。 push()メソッドは引数5で呼び出され、 arr Arrayの最後に5追加します。
push()メソッドは、要素の追加後に配列の新しい長さを返します。この場合、 5アレイの端に追加されるため、Arrの新しい長さは5になります。
let arr = [ 3 , 5 , 7 , 9 ]
let result = arr . unshift ( 1 , 2 )
console . log ( 'result: ' , result , 'arr: ' , arr )上記のコードスニペット出力は何ですか?
JavaScriptのarray.unshift()メソッドは、配列の先頭に1つ以上の要素を追加し、配列の新しい長さを返します。
指定されたコードでは、 arrは値[3, 5, 7, 9]を持つ配列です。 unshift()メソッドは、引数1と2で呼び出されます。これにより、 arr配列の先頭に1と2が追加されます。
unshift()メソッドは、要素の追加後に配列の新しい長さを返します。この場合、1と2が配列の先頭に追加され、既存の要素を右にシフトするため、 arrの新しい長さは6になります。
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()メソッドは、 10であるarr Arrayから最初の要素を削除し、返します。結果のarr配列は[20, 30, 40, 50]になります。
したがって、オプションAは、 removedElementの正しい値とArray.shift()後のarrの更新状態を反映しているため、正解です。オプションBは、 removedElement 50になると述べているため、間違っていますが、これは真実ではありません。また、 arr変更されていないため、正確ではないと述べているため、オプションCも間違っています。 Array.shift()が配列を返すと述べているため、オプションDはわずかに混乱していますが、これは真実ではありません。
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」が配列に2回表示され、最後の発生はインデックス4であるため、 lastIndex 4になります。
一方、 Array.includes()メソッドは、指定された値「grape」がアレイ果実に存在するかどうかをチェックし、「grape」が配列に存在するため、 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で割り切れる任意のnumsに対してtrueを返します。Numsアレイでは7とnums.filter(isDivisibleBy7)が7で割り切れます。
Array.find()メソッドは、関数に渡されたアレイの最初の要素を返します。この場合、それに渡された関数は10未満の任意の数値に対して真で返されます。10未満のnumsには複数の数値がありますが、 Array.find() trueでnums.find((num) => num < 10)もののみを返します。
Array.findIndex()メソッドは、 Array.find()メソッドに似ていますが、関数に渡されたアレイの最初の要素のインデックスを返します。この場合、28 /2 == nums.find((num) => num / 2 == 14)はアレイnumsにあり、インデックス0にあるため、28に渡された関数は28でtrueを返します。
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() 、各要素に関数を繰り返し適用し、蓄積された結果を追跡することにより、配列を取得し、単一の値に「削減」します。これは、数値の配列を合計したり、最大値を見つけたり、文字列の配列を単一の文字列に連結したりするなどのタスクに一般的に使用されています。
この場合、resid()メソッドは、配列の各要素に対して実行されるコールバック関数を取ります。コールバック関数には、 accとval 2つのパラメーターが使用されます。これは、それぞれアレイのアキュムレータと現在の値を表します。
コールバック関数内で、配列の現在の値がアキュムレータに追加され、結果が返されます。 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()メソッドは、現在の要素currにアキュムレータaccを追加するコールバック関数を使用してこの配列で呼び出されます。
最初の反復では、初期値が提供されていないため、 curr値は4であり、ACC値はundefinedなります。したがって、最初の反復の結果は4なります。
2回目の反復では、 curr値は3であり、 acc値は以前の反復の結果であり、 4です。したがって、2回目の反復の結果は7なります。
3回目の反復では、 curr値は2であり、 acc値は以前のイテレーションの結果であり、 7です。したがって、3回目の反復の結果は9なります。
4番目の最終的な反復では、 curr値は1であり、 acc値は以前の反復の結果であり、 9です。したがって、4回目の反復の結果は10なります。
したがって、コードの最終出力は10なります。したがって、正しいオプションはAです。
const arr = [ 'Centauri' , 3.14159 , 'canine' , 11235 , undefined ]
const result = arr . sort ( )
console . log ( result )上記のコードスニペット出力は何ですか?
デフォルトでは、 sort()メソッドは文字ごとに要素をソートするため、11235が3.14159より前に来るので、1は3より前になります。
単語と文字はASCIIコードによってアルファベット順にソートされるため、大文字C(ASCIIコード67)から始まる「Centauri」(ASCIIコード67)は、小文字C(ASCIIコード99)で始まる「犬」の前に並べ替えます。
未定義の要素は、常に配列の端まで並べ替えます。
したがって、コードの最終出力は[11235、3.14159、 'Centauri'、 'canine'、未定義]です。これはオプション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番目の要素に対応します。これは3です。
配列内の要素がundefined場合、変数のデフォルト値を設定することができます。配列の4番目の要素は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()現在の日付と時刻を返し、その後に2つの指定された日付がフォーマット「yyyy-mm-ddthh:mm:ss.ssz」で返されます。ここで、「z」はUTCタイムゾーンオフセットを表します。
YYYY-MM-DDTHH:mm:ss.sssZ ISO 8601標準の日付と時間を表すために使用される形式です。次のコンポーネントで構成されています。
YYYY :4桁の年(0000〜9999)、または +または - 6桁の拡張年として。標識は拡大した年に必要です。 -000000は、有効な年として明示的に禁止されています。MM :2桁の月(01 = 1月、02 = 2月など)。デフォルトは01です。DD :月の2桁の日(01〜31)T :時間コンポーネントの開始を示すセパレーターHH :24時間形式(00〜23)で1日の2桁の時間。特別なケースとして、24:00:00は許可されており、翌日の初めに真夜中と解釈されます。デフォルトは00になります。mm :時間の2桁の分(00〜59)。デフォルトは00になります。ss :2桁の2桁の1分(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の返します。
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オブジェクトを使用して2つの日付を作成します。Date1 date1 2023年5月1日を表し、 next_us_election 2024年11月5日を表します。
getTime()メソッドは、各日付のミリ秒単位で時間値を取得するために使用されます。 next_us_electionからdate1の時間値を差し引くことにより、ミリ秒で時差が得られます。
時間差をミリ秒から日に変換するために、1日(1000 _ 3600 _ 24)でミリ秒数で割っています。結果は、可変difference_in_daysに保存されます。
最後に、 parseInt()関数は、違いの違いを整数に変換するために使用され、結果は「日」文字列とともにコンソールにログに記録されます。出力は「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 ( )上記のコードスニペット出力は何ですか?
コードは、 name 、 age 、 hobbies 、 addressなどのプロパティを持つオブジェクトリテラルperson 、およびsayHelloメソッドを定義します。
console.log()ステートメントは、 nameの値、 hobbies配列の2番目の要素(「旅行」です)、およびaddress内のcityプロパティの値(「ニューヨーク」)の値を印刷します。
最後に、 sayHelloメソッドは、ドット表記を使用してpersonオブジェクトで呼び出され、文字列「こんにちは、私の名前はジョンです」をコンソールに出力します。
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を定義します。 2つのuserオブジェクト、 user1とuser2は、それぞれ初期のユーザー名「kirandash」と「bgwebagency」で作成されます。
updateUsernameメソッドは、 user1とuser2オブジェクトの両方で呼び出され、ユーザー名を更新します。 user1のユーザー名は「kirandash-website」に更新され、 user2のユーザー名は「bgwebagency-app」に更新されます。
最後に、コードはuser1.usernameとuser2.usernameの連結を記録します。これにより、出力「kirandash-website bgwebagency-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' )上記のコードスニペット出力は何ですか?
The call function is used to invoke the greet function with the person object as the context (the value of this ) and 'John' as the argument.
The apply function is used to invoke the greet function with the person object as the context (the value of this ) and an array ['Alex'] as the arguments.
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 )