preface

These two years the front end is very popular, JavaScript is the front end of the skills, there are actually some interesting small skills and methods in JavaScript development, this article recorded some of my work encountered some skills and methods.

The body of the

Generates a random number within a specified range

When we need to get the specified range
(min,max)When integers are inside, the following code is very suitable; That’s a lot of code to use.

function setRadomNum(min,max){
    return  Math.floor(Math.random() * (max - min + 1)) + min;
}Copy the code

Json to URL parameter

This code comes in handy when you need to convert JSON to URL parameters for HTTP requests.

function json2url(json) {
    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    }
    return arr.join('&');
}Copy the code

Verify that it is an array

function isArray(obj){
    return Array.isArray(obj) || Object.prototype.toString.call(obj) === '[object Array]';
}Copy the code

Check to see if it’s locally available
Array.isArrayFunction without performing the following method checks.

Empty array

Var arr=[1,2,3,4,5]; arr.length=0; Var arr=[1,2,3,4,5]; arr.splice(0,arr.length); Var arr=[1,2,3,4,5]; arr=[];Copy the code

Method three assigns a reference to a new array to the variable, leaving the other references unaffected. This means that references to the contents of the previous array will remain in memory, causing a memory leak.
The most efficient way is the first oneSo the first method is recommended for emptying the array.

Preserves the specified decimal place

This requirement is also common in projects and can be toFixed()

Var num = 3.1415926; num = num.toFixed(4); Console.log (num); //toFixed() rounds the Number to a specified decimal Number. Console.log (num); / / 3.1416Copy the code

Shuffle the array order

Arr.sort (function(){return math.random ()-0.5}); Function shuffle(arr) {var I, j, temp; function shuffle(arr) {var I, j, temp; for (i = arr.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; };Copy the code

Method 1 uses the built-in sorting method for arrays:
sort, and the second method is to use an intermediate quantity, two values in a random number set, let them exchange positions.

Use === instead of ==

== (or! The =) operation performs the type conversion automatically if needed. = = = or! The ==) operation does not perform any conversion. === is arguably faster than == when comparing values and types.

[10] = = 10 / / to true [10] = = = 10 / / to false '10' = = 10 / / to true '10' = = = 10 / / to false [] = = 0 / / to true [] = = = 0 / / False "== false // true but true == "a" == false" === false // FalseCopy the code

Use “&” and “| |”

||and
&&Operator clever use, can be used to simplify the code, reduce the readability of the program.

For assignment && : judging from left to right, when the current value is true, false returns this value (is returned not converted to Boolean values when the original value of oh) | | : judging from left to right, when the current value of false continues, to true is returned this value (is returned not converted to Boolean values when the original value of oh)

var attr = true && 4 && "aaa"; //aaa;
var attr = true && 0 && "aaa"; //0
var attr = 100 || 12; //100
var attr = "e" || "hahaha" //'e'
var attr = "" || "hahaha" //'hahaha'Copy the code

Used for conditional execution statements

// The normal if statement if(test){isTrue(); } // The above statement can be written with '&&' as: (test && isTrue()); test = false; if(! test){ isFalse(); } / / the above statements can use '| |' written as follows: (the test | | isFalse ());Copy the code

Used to assign values after multiple judgments

var add_level = 0; if(add_step == 5){ add_level = 1; } else if(add_step == 10){ add_level = 2; } else if(add_step == 12){ add_level = 3; } else if(add_step == 15){ add_level = 4; } else { add_level = 0; } / / can be written as var add_level = (5 && add_step = = 1) | | (10 && add_step = = 2) | | (12 && add_step = = 3) | | (15 && add_step = = 4) | | 0;Copy the code

Gets the maximum or minimum value in the array

function maxAndMin(arr){
    return {
       max:Math.max.apply(null,arr.join(',').split(',')),
       min:Math.min.apply(null,arr.join(',').split(','))
    }
}Copy the code

This method is suitable for one-dimensional or multidimensional arrays.

Gets the elements of the array randomly

function getRadomFromArr(arr){
    return arr[Math.floor(Math.random()*arr.length)];
}Copy the code

Retrieves the specified value from an array

If found, return
true, no check return
false.

function findInArr(arr, value){
	for (var i=0; i<arr.length; i++){
		if (arr[i] == value){
			return true;
		}
	}	
	return false;
}Copy the code

Generates a random alphanumeric string of the specified length

function getRandomStr(len) {
    var str = "";
    for( ; str.length < len; str  += Math.random().toString(36).substr(2));
    return  str.substr(0, len);
}Copy the code

Removes whitespace from the string

Although the trim method is implemented in ECMAScript5, it is not supported in older browsers, so we sometimes need to implement it ourselves.

Remove leading and trailing Spaces

function trim(str){
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
trim('  hello world    '); //"hello world"Copy the code

Remove all Spaces

function trimAll(str){
    return str.replace(/\s+/g,"");
}
trimAll('   he ll o  wo  r ld    '); //"helloworld"Copy the code

Afterword.

JavaScript inside certainly still have a lot of skills, later encountered slowly summary. JavaScript is deep, and I feel like I still have a lot to learn. Come on!!