Front-end development interview questions (fresh students) -- js basic algorithm questions

foreword

        This article brings together some basic algorithm problems of js. Many Internet companies like to ask candidates to do some js algorithm problems when recruiting junior front-end development engineers (fresh students). At this time, if you have learned the solutions of these js basic algorithm problems The ideas of the questions are very helpful to you, and some of them can even be directly applied. Therefore, it is recommended that fresh students must read them before the interview.

topic

Problem 1: Flip a string.

Problem-solving ideas: 1. split() the string into an array; 2. reverse() to flip the array; 3. join() the array into a string.

function reverseString(str){
    var str=str.split("").reverse().join(""); //String into array. Flip array. Array into string
    return str; //return value
}
alert(reverseString("hello world!")); //Output result: !dlrow olleh


Problem 2: Factorial.

Method 1: while method

function factorialWhile(num){
    var result = 1;
    while(num){
    result*=num;
    on one--;
    }
    return result;
}
alert(factorialWhile(5)); //Output result: 120

Method 2: for method

function factorialFor(num){
    if(num<1){
        return 1;
    }else{
        for(var i=num-1; i>=1; i--){
            num*=i;
        }
    }
    return num;
}
alert("for method 2: "+factorialFor(5)); //output result: 120

Method 3: Recursive method

function factorial(num){
    if(num<1){
       return 1;
    }
    else{
        return num*factorial(num-1);
    }
}
alert("Recursive method three: "+factorial(5)); //Output result: 120


Question 3: If the given string is a palindrome, return true, otherwise, return false.

Palindrome: A string is a palindrome if it reads exactly the same forward and backward, ignoring punctuation, capitalization, and spaces.

Problem-solving idea: remove the extra punctuation marks and spaces from the string, and then convert the string to lowercase to verify whether the string is a palindrome.

function palindrome(str){
    var str1 = str.replace(/[^0-9a-zA-Z]/g,"").toLowerCase(); //Remove punctuation, convert to lowercase, compare parameter one
    //alert(str1); //Output: abc1d42efg000h000gfe24d1cba
				
    var str2 = str1.split("").reverse().join(""); //Reverse the string, compare the second parameter
    //alert(str2); //Output: abc1d42efg000h000gfe24d1cba
				
    if (str1 === str2) {
        return true;
    } else{
        return false;
    }
}
alert(palindrome("aBc,./1d42--==EFG0 00 h0-';'00gfE';./. 24d 1cBA")); //Output result: true


Question 4: Find the longest word in the provided sentence and calculate its length.

Problem-solving ideas: 1. Convert into an array; 2. Sort according to the length of the elements; 3. Output the longest element and return the length.

function findLongestString(str){
    var arr = str.split(" "); //Convert into an array, note that there is a space in the split() brackets
    //alert(arr); //Output: I,love,China
    var aSort = arr.sort(function (a,b){ //sort
        return b.length-a.length;
    });
    //alert(aSort); //Output: China,love,I
    document.write("Longest word: "+aSort[0]+"; "); //The first element is the longest
    document.write("Word length: "+aSort[0].length);
}
findLongestString("I love China"); //Output result: longest word: China; word length: 5


Question 5: Make sure the first letter of each word in the string is capitalized and the rest is lowercase.

Problem-solving ideas: 1. Convert the string to lowercase; 2. Divide it into a string array; 3. The new combined string element = the first letter to uppercase + the rest of the lowercase.

function titleCase(str){
    var aStr = str.toLowerCase().split(" "); // Convert to lowercase and split into string arrays		
    for(var i=0; i<aStr.length; i++){
        aStr[i] = aStr[i][0].toUpperCase()+aStr[i].slice(1); //Reassemble string elements
    }
    var oString = aStr.join(" "); //convert to string										
    return oString;
}
document.write(titleCase("I'm a title Case."));    //输出结果:I'm A Title Case.


Question 6: A large array contains 4 small arrays, find the maximum value in each small array, and then concatenate them to form a new array.

Problem-solving idea: Find the maximum value in each small array, and store the maximum value in a new array for output.

Method 1: Use the Math.max.apply() method to extract the maximum value

function largestArray(arr){
    var result = []; //Used to store the largest number in the four small arrays
    for (var i=0; i<arr.length; i++) {
        result.push(Math.max.apply(null, arr[i])); //Find the maximum value among the four small arrays, then insert into the new array
    }
    return result;
}
document.write(largestArray([[165,2,9], [48,6,9,82],[6,5],[29658,91,2]])+"</br>");/ /output result: 165,82,6,29658

Method 2: Sorting method to extract the maximum value

function largestArr(arr){
    var result = [];
    for (var i=0; i<arr.length; i++) {
        arr[i].sort(function(a, b) { //sort the four small arrays, from large to small
            return b-a;
        });
    result.push(arr[i][0]); //Add the first (largest) of the four small arrays to result
    }
    return result;
}
document.write(largestArr([[165,2,9], [48,6,9,82],[6,5],[29658,91,2]])+"</br>");/ /output result: 165,82,6,29658    


Question 7: Check if a string (str) ends with the specified string (target). If it is, return true; if not, return false.

Problem-solving idea: Intercept the end of the string (the length is the same as the target) and compare it with the target.

function confirmEnding(str, target){
    var len = target.length;				
    var strEnding = str.slice(-len); //cut the last few characters of the string		
    if (strEnding == target) {
        return true;
    } else{
        return false;
    }
}
document.write(confirmEnding("strawberry", "rry")); //Output result: true


Question 8: Repeat a specified string num times, and return an empty string if num is a negative number.

function repeat(str, num){
var result=str; //Assign the initial value to result
    if (num<=0) {
        return "";
    } else{
        for (var i=0; i<num-1; i++) { //The index starts from 0 and loops num-1 times; (the number of occurrences includes itself, so only need to loop num-1 times)
            result+=str;		
        }
        return result;
    }			
}
document.write(repeat("love", 3)); //Output result: lovelovelove


Question 9: Truncate a string. If the length of the string is longer than the specified parameter num, the excess part is represented by ....

Problem-solving idea: intercept the string of the corresponding length, and then splicing it with ....

  • The specified length does not include...
function truncate(str, num){
    var aStr = str.slice (0, num);
    if (str.length > num) {					
        return aStr.concat("...");
    }
    else{
        return str;
    }
}
document.write(truncate("javascript", 8)+"</br>");    //输出结果:javascri...
  • The specified length includes...
function truncate(str, num) {
    var str1 = str.slice (0, num-3);
    var str2 = str.slice (0, num);
    if(str.length > num){
        if(num<=3){
            return str2+'...';
        }else{
            return str1+'...';
        }
    }else{
        return str;
    }
}			
document.write(truncate("javascript", 8)); //Output result: javas...

Question 10: Divide an array arr into several array blocks according to the specified array size size.

Problem-solving idea: define an empty array, use slice() to intercept size elements of the original array each time and insert it into the empty array to form a new array.

function chunk(arr, size){
    var Array = [];
    if (arr.length > size) {							
        for (var i=0; i<arr.length; i+=size) { //size elements per loop
            Array.push("["+arr.slice(i,i+size)+"]"); // Each time the size element is intercepted and added to the Array ([] is added for the convenience of observation)					
        }
        return Array;
        } else{
            return "["+arr+"]";
}				
    }document.write(chunk([1,2,3,4,48,666],2)); //Output result: [1,2],[3,4],[48,666]


Question 11: Return the remaining elements of an array that is truncated by n elements, starting at index 0.

function slasher(arr, n){
    var Array = [];
    if (n<=0) {
        return arr;
    } else{
    Array.push(arr.slice(n));				
        return Array;
    }	
}
document.write(slasher([1,516,15,85,3,841], 3)); //Output result: 85,3,841


Question 12: The function returns true if the first string element of the array contains all the characters of the second string element.

Explanation: ["hello", "Hello"] should return true because all characters of the second string can be found in the first string regardless of case.

function mutation(arr){
    var str1 = arr[0].toLowerCase();
    var str2 = arr[1].toLowerCase();
    for (var i=0; i<str2.length; i++) {
        if (str1.indexOf(str2[i]) <= -1) { //There are elements in str2 that cannot be found in str1
            return false;					
        }
    }
    return true;
}			
document.write(mutation(["Hello", "hey"])); //Output result: true

Explanation of indexOf() method : Returns the position where a specified string value appears for the first time in the string.

语法:stringObject.indexOf(searchvalue,fromindex)

Keyword: searchvalue, required, specifies the string value to be retrieved

     fromindex, optional, retrieves from the index of the string

Return value: Returns the position where the specified value appears for the first time in the string. If it returns -1, the string does not contain the changed value.


Question 13: Remove all false values ​​in an array. In JavaScript, false values ​​are false, null, 0, "", undefined, and NaN.

function bouncer(arr){
    return arr.filter(test); //filter method filters to get the values ​​that meet the conditions
}
// conditional function
function test(ele){
    var count = he !== false || he !== null || he !== 0 || he !== "" || he !== undefined || he !==NaN;
    if (cont) { //if cont holds
        return it;
    }				
}			
document.write(bouncer([561, "hello", true, false, ""]));    //输出结果:561,hello,true

Array.filter() : Checks the array to get all elements that meet the specified condition (fn).

语法:array.filter(function(currentValue,index,arr), thisValue)

Keywords: currentValue, required, the value of the current element; index, optional, the index of the current element; arr, optional, the array to which the current element belongs. thisvalue, optional, the object to use when the callback is executed, passed to the function, to be used as the value of "this". If thisValue is omitted, the value of "this" is "undefined"


Check out more js interview questions: https://blog.csdn.net/mr_javascript/article/details/79769572

-------------------------------------------- end ----------------------------------------------

Reference article: https://www.cnblogs.com/mr-wuxiansheng/p/6534910.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325492620&siteId=291194637