preface
Recently ushered in the upsurge of spring recruitment, I believe that many students are preparing for spring recruitment, I am also actively preparing, want to consolidate the JS foundation again, the JS method summary. But it is not desirable to rely on rote memorization, to learn the specific use of the brush in the scene to remember a JS method call. This article is the brush encountered in the common JS methods summed up.
When I first started learning JavaScript, I used to brush Codewars a lot, which was very useful for learning JavaScript syntax, and also because I found it hard to brush LeetCode at first.
toString()
1. Convert a number to a string.
2. Convert to base number, write ‘2’ in parentheses, can be converted to binary number.
-
Title: Implement a function that adds two numbers together and returns their sum in binary form. The conversion can be done before or after the addition. The binary number returned should be a string.
Solution code:
Function addBinary(a,b) {return (a+b).tostring (2)} console.log(addBinary(1,8));Copy the code
Output result:
split()
Splits a string into an array of strings.
-
Title: Write a function that takes an integer as input and returns the number of bits equal to 1 in the binary representation of that number. You can guarantee that the input is non-negative.
Example: the binary representation of 1234 is 10011010010, so 5 in this case the function should return
Solution code:
var countBits = function(n) {
return n.toString(2).split('0').join('').length
};
Copy the code
repeat()
String copied a specified number of times.
- Title: Build Tower; The tower is built with the following given parameters: the number of floors (an integer, always greater than 0). For example, a six-story tower
[' * 'and' * * * ', '* * * * *', '* * * * * * *', '* * * * * * * * *', '* * * * * * * * * * *']Copy the code
Solution code:
function towerBuilder(nFloors) { var arr=[] for(let i=0; i<nFloors; i++){ arr.push(" ".repeat(nFloors-i-1)+"*".repeat(2*i+1)+" ".repeat(nFloors-i-1)); } return arr; }Copy the code
replace()
Replace some characters in a string with other characters, or a substring that matches the regular expression.
- Title: Your task is to write a function that takes a string and returns a new string with all vowels removed.
For example, the string “This website is for losers LOL!” “Ths WBST s FR LSRS LL!” .
Solution code:
function disemvowel(str) {
return str.replace(/[aeiou]/gi, '');
}
Copy the code
The use of replace()+ re makes the code very neat and elegant.
trim()
Used to delete the beginning and end whitespace of a string. Whitespace includes Spaces, tabs, newlines, and other whitespace characters.
Note: not applicable to null, undefined, Number types.
- Title: Dubstep; For example, songs with the word “IAM X” can be converted to a remix of “WUBWUBIWUBAMWUBWUBX”, not “WUBWUBIAMWUBX”.
Such as:
songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
// => WE ARE THE CHAMPIONS MY FRIEND
Copy the code
Solution code:
function songDecoder(song){
return song.replace(/(WUB)+/g," ").trim()
}
Copy the code
match()
You can retrieve a specified value within a string or find a match for one or more regular expressions
- Check if the string contains the same number of “x” and “O”. This method must return a Boolean value and be case insensitive. The string can contain any character.
Such as:
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
Copy the code
Solution code:
let x = str.match(/x/gi);
let o = str.match(/o/gi);
return (x && x.length) === (o && o.length);
Copy the code
toUpperCase()
ToUpperCase () is used to convert a string toUpperCase.
The toLowerCase() method is used to convert a string toLowerCase.
- Title: RGB function is incomplete. Complete it so that passing an RGB decimal value will result in a hexadecimal representation being returned. RGB has valid decimal values ranging from 0 to 255. Any values outside this range must be rounded to the nearest valid value.
Such as:
RGB (255, 255, 255) // returns FFFFFF RGB (255, 255, 300) // returns FFFFFF RGB (0,0,0) // Returns 000000 RGB (148, 0,0, 211) // returns 9400D3Copy the code
Solution code:
function rgb(r, g, b){
// complete this function
r=a(r);
g=a(g)
b=a(b)
let arr=r.toString(16).toUpperCase()+g.toString(16).toUpperCase()+b.toString(16).toUpperCase()
console.log(arr);
}
function a(n){
if(n>255){return n=255}
else if(n<=0){return n='00'}
else{return n}
}
Copy the code
for in
for… The IN statement is used to iterate over an array or an object’s properties (loop over an array or an object’s properties).
- Title: Modern Roman numerals are written in such a way that each number is represented separately, starting with the leftmost number, and then skipping any zero values.
Such as:
solution(1000); // should return 'M'
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Copy the code
Solution code:
function solution(number){ // convert the number to a roman numeral var roman = {M:1000,CM:900, D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1 } var ans = ''; while(number>0){ for(a in roman){ if(roman[a]<=number){ ans += a; number-=roman[a]; break; } } } return ans; }Copy the code
forEach
Used to call each element of the array and pass the element to the callback function.
- An interval is represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval Example: [1, 5] Interval from 1 to 5. The length of this interval is 4.
Example:
[[1,2], [6, 10], [11, 15]]); / / = > 9 sumIntervals ([[1, 4], [7, 10], [3, 5]]). / / = > 7 sumIntervals ([[1, 5], [10, 20], [1, 6], [16, 19], [5, 11]]). / / = > 19Copy the code
Solution code:
function sumIntervals(intervals){ //TODO var numbers ={} intervals.forEach(function(x){ for(var i =x[0]; i<x[1]; i++){ numbers[i]=i } }) // return Object.keys(numbers).length return numbers }Copy the code
map()
The map() method returns a new array, leaving the original array unchanged. The elements in an array are the values processed by the original array element.
The map() method processes the elements in their original array order.
-
Title: The number 89 is the first integer with more than one digit that satisfies the attributes introduced in part of the kata title.
Valid: 89 = 8^1 + 9^2
The next number with this property is 135.
Look at this property again: 135 = 1^1 + 3^2 + 5^3
Such as:
sumDigPow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
sumDigPow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
Copy the code
Solution code:
function sumDigPow(a, b) { // Your code here var res=[] var arr,sum =0 for(let i=a; i<=b; i++){ arr=i.toString().split('').map(Number) sum=0; for(let j=0; j<arr.length; j++){ sum +=Math.pow(arr[j],j+1) } if(i===sum){ res.push(i) } } return res }Copy the code
reduce()
Receiving a function as an accumulator, each value in the array (from left to right) is reduced to a value.
Note: can be used as a higher-order function for compose of the function
Another way to solve the previous problem:
function sumDigPow(a, b) { var ans = []; While (a < = b) {/ / reduce () accumulate the if (a.t oString (). The split (' '). The reduce ((x, y, I) = > x + (+ y) * * (I + 1), 0) = = a) ans. Push (a); a++; } return ans; }Copy the code
indexOf()
Returns the position at which a specified string value first appears in a string.
- Title: There is a self-checkout queue in the supermarket. Your task is to write a function that calculates the total time it takes for all customers to check out!
Example:
QueueTime ([5,3,4], 1) // should return 12 // because when there is 1 till, The total time is just the sum of The Times queueTime([10,2,3,3], 2) // should return 10 // because here n=2 and the 2nd, 3rd, And 4th people in the queue finish before the 1st person has finished. QueueTime ([2,3,10], 2) // should return 12Copy the code
Solution code:
let temp = Array(n).fill(0) customers.map(item => { let idx = temp.indexOf(Math.min(... temp)) temp[idx] += item }) return Math.max(... temp)Copy the code
Some simple commonly used JS methods
Here are some of the js methods that need to be interspersed in solving the problem. It is relatively simple and basic. It is not a waste of time to take out the topic.
- CharAt number of start index
//chatAt
var s="I am xiaochen"
console.log(s.charAt(6))
Copy the code
Execution Result:
- Slice retrieves the selected element by position from an existing array. (As opposed to the split() method)
Var arr=[1,2,3,4,5,6] var res=arr.slice(2,5)Copy the code
Execution Result:
- Join Puts all the elements in an array into a string.
//join var arr=['I', 'am', 'xiaochen'] console.log(arr.join(' ')Copy the code
Execution Result:
conclusion
Found that before feel more fuzzy JS method, their hand knock again, check the execution results, can be more solid memory. In fact, these methods are not difficult, but when properly applied in a topic, such as Scrolling Codewars, I can simplify a large amount of code into a few lines of code, or even a single code, which is very magical and inspires me to learn JS in depth. This article is a summary of the JS methods I often encounter in the brush, the most important or in the use of specific scenes.
I also strongly recommend that those of you who are new to JavaScript check CodeWars. CodeWars doesn’t require a lot of questions to check, and scores will determine your level based on the code you write. It’s fun.
I am a junior in school, preparing for spring enrollment, if you have a partner to study with, welcome to add my friend duck! wx:chen0105123