The first is a few problems encountered
The first question
Let arr = [0,1,2,2,3,3,3,4,4,4,4,6] let arr2 = arr.map console.log(arr2)Copy the code
Complete the parentheses so that console.log(arr2) prints the result as
The console. The log (arr2) / / results for [' Sunday ', 'Monday', 'on Tuesday, Tuesday, Wednesday, Wednesday, Wednesday, Thursday, Thursday, Thursday,' on Thursday, 'Saturday]Copy the code
The first is my own solution, the code is as follows
Let arr =,1,2,2,3,3,3,4,4,4,4,6 [0] let arr2 = arr. The map (x = > {the if (x = = = 0) {return x = 'Sunday'} else if (x = = = 1) {return x Else if(x === 3){return x = 'Wednesday'}else if(x === 4){return x = 'Thursday' }else{return x = 'Saturday'} return x}) console.log(arr2)Copy the code
Although this code can be implemented, the number of lines of code is too long, it is not beautiful and looks not professional. After searching engines and consulting friends, we changed it to a more beautiful writing method, and the code is as follows
Let arr =,1,2,2,3,3,3,4,4,4,4,6 [0] let arr2 = arr. The map ((item) = > {return [' Sunday ', 'on Monday, Tuesday, Wednesday, Thursday, Friday,' Saturday] [items]}) console.log(arr2)Copy the code
The code in line 3 says, given an array from Sunday to Monday, iterate through the array using the item in arr, whose elements [0,1,2,3,4,6] correspond to the subscript of the array.
Such as:
- Sunday is subscript 0, so arR2’s first element is Sunday.
- Monday is subscript 1, so all the ones in ARR2 are Monday.
- Wednesday is subscript 3, so all three elements of ARR2 are Wednesday.
The second question
Let scores =,91,59,55,42,82,72,85,67,66,55,91 [95] let sum = scores. The reduce ((sum, n) = >} {the completion code, 0) to the console. The log (sum)Copy the code
Complete the code so that it prints the sum of all odd numbers
Console. log(sum) // Sum of odd numbers: 598Copy the code
The first is my solution, which looks like this
Let scores =,91,59,55,42,82,72,85,67,66,55,91 [95] let sum = scores. Reduce ((sum, n)=>{ if( n%2 === 1 ){ return sum+n }else{ return sum } },0) console.log(sum)Copy the code
The problem of this code is still too many lines, which looks not beautiful. After adjustment, the code is as follows
Let scores =,91,59,55,42,82,72,85,67,66,55,91 [95] let sum = scores. Reduce ((sum, n) = > {return n % 2 = = = 1? sum+n : sum },0) console.log(sum)Copy the code
If the scores array is odd, sum+n is returned. Otherwise, sum is returned. The comma followed by the curly bracket and the 0 enclosed in the closing bracket indicate that sum starts at 0.