Skip to main content

Posts

箭头函数和rest参数

  const   sum = (... args )=>{ let   total  =  0 ;    for  ( let   i = 0 ; i < args . length ; i ++)   {      total += args [ i ];   }    return   total ; } ES6 spread操作符,中文翻译为扩展操作符。 const   arr1  = [ 'JAN' ,  'FEB' ,  'MAR' ,  'APR' ,  'MAY' ]; let   arr2 ; arr2  = [... arr1 ];   // Change this line console . log ( arr2 );

Use Recursion to Create a Range of Numbers

  function   rangeOfNumbers ( startNum ,  endNum ) {    if ( startNum <= endNum )   {      const   arrNumber  =  rangeOfNumbers ( startNum ,  endNum - 1 );      arrNumber . push ( endNum );      return   arrNumber ;   }    else  {      return  [];   }       }; console . log ( rangeOfNumbers ( 6 , 8 ));//[6,7,8] console . log ( rangeOfNumbers ( 3 , 12 )); //[ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

Use the parseInt Function with a Radix

The   parseInt()   function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36. The function call looks like: parseInt ( string , radix ) ; And here's an example: const a = parseInt ( "11" , 2 ) ; The radix variable says that  11  is in the binary system, or base 2. This example converts the string  11  to an integer  3 . 基数是2,说的是2进制,所以二进制的11,就是十进制的3. I t converts a binary number to an integer and returns it

recursive in javascript

 递归的思想:取出当前的值,递归当前值以前的所有值。 function   sum ( arr ,  n ) {      let   total = 0 ;    if ( n <= 0 ){      total = 0 ;   } else if (n>arr.length) { return undefined; }       else {      total = arr [ n - 1 ]+ sum ( arr , n - 1 )   }    return   total ;    } console . log ( sum ([ 1 , 3 , 5 ], 3 )); 先考虑极端情况,只有一个元素或者没有元素的情况,那么直接返回0,如果超出了arr的length,则返回无定义 其他情况取当前元素,加上所有以前元素的和。 第二个例子,阶乘, function   factorialize ( num ) {    let   factor  =  0 ;    if  ( num <= 0 ){      factor  =  1 ;   }    else   {      factor  =  num *( factorialize ( num - 1 ));   }    return   factor ; } factorialize ( 5 );