Js工具類
3550 ワード
もっと読む
Js工具類
常用方法の整理は以下の通りです.
Js工具類
常用方法の整理は以下の通りです.
/* */
function randomSort() {
return Math.random() > .5 ? -1 : 1;
}
/* */
function randomArr(sourceArr, length, zeroFlag) {
var targetArr = [];
var arrTemp1 = sourceArr.concat();
var arrTemp2 = sourceArr.concat();
for(var i = 0; i < length; i ++) {
var index = 0;
if(zeroFlag) {
index = randomArrVal(arrTemp1);
} else {
index = randomArrVal(arrTemp1) - 1;
}
targetArr.push(arrTemp2[index]);
}
return targetArr.sort();
}
/* */
function randomArrVal(sourceArray) {
//
var arrIndex = Math.floor(Math.random() * sourceArray.length);
var arrValue = parseInt(sourceArray[arrIndex]);
sourceArray.splice(arrIndex, 1);
return arrValue;
}
/* , */
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
}
/* , */
Array.prototype.in_array = function(e)
{
for(var i = 0; i < this.length; i++)
{
if(this[i] == e)
return true;
}
return false;
}
/* ,n ,m */
function permutation(n, m) {
var front = 1;
for(var i = 0 ; i < n; i++){
front = front * (m - i);
}
return front;
}
/* ,n ,m */
function combination(n, m){
var front = 1;
for(var i = 0 ; i < n; i++){
front = front * (m - i);
}
var back = 1;
for(var i = 1; i <= n; i++){
back = back * i;
}
return front/back;
}
/* */
function combinationSplit(sourceArr, count) {
var result = [];
if(null != sourceArr && sourceArr.length >= count && count >0 ){
var tempArr = [];
combineRecursion(sourceArr, 0, count, tempArr, result);
}
return result;
}
/* */
function combineRecursion(arr1, begin, number, arr2, arr3) {
if(number == 0) {
var tempArr = arr2.concat()
arr3.push(tempArr);
return;
}
if(begin == arr1.length) {
return;
}
arr2.push(arr1[begin]);
combineRecursion(arr1, begin + 1, number - 1, arr2, arr3);
arr2.remove(arr1[begin]);
combineRecursion(arr1, begin + 1, number, arr2, arr3);
}
/* */
function trimAll(str,is_global)
{
var result;
result = str.replace(/(^\s+)|(\s+$)/g,"");
if(is_global.toLowerCase()=="g")
{
result = result.replace(/\s/g,"");
}
return result;
}
/* */
function initArr(length, val) {
var arr = [];
for(var i = 0 ; i < length; i++){
arr.push(val);
}
return arr;
}