Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created February 17, 2014 16:00
Show Gist options
  • Select an option

  • Save adohe-zz/9053249 to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/9053249 to your computer and use it in GitHub Desktop.
some useful pieces of code in JS
1.Get a random item from an array
var arr = [1, 2, 3, 4, 5];
var item = arr[Math.floor(Math.random() * arr.length)];
2.Get a random number in a specific range
var item = Math.floor(Math.random() * (max - min + 1)) + min;
3.Generate a random set of alphanumeric characters
function generate(len) {
var randomString = "";
for(; randomString.length < len; randomString += Math.random().toString(36).substr(2));
return randomString.substr(0, len);
}
4.Generate an array of numbers with numbers from 0 to max
var numberArr = [], max = 100;
for(var i = 1; numberArr.push(i++) < max; ;);
5.A string trim function
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};
6.Append an array to another
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
Array.prototype.push.apply(arr1, arr2);
7.Transform the arguments object to array
var argArray = Array.prototype.slice.call(arguments);
8.Verify that a given argument is a number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment