为您的前端/网络编码访谈学习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' )上述代码片段输出什么?
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 )