11.数组等分切片:
this.newMapList = [];
for (var i = 0; i < this.mapDataList.length; i += 2) {this.newMapList.push(this.mapDataList.slice(i, i + 2));
}
12.js做奇偶判断:
if (this.mapDataList.length != 0) {this.mapDataList.length % 2 == 0 ? this.isEven = true : this.isEven = false;
}
13.js判断 元素 urls 是否为数组 :
let isarr = Object.prototype.toString.call(urls) === '[object Array]';
14.递归查找子对象或者组件:
/**
* 递归查找
* @param sp
* @param name
*/
public static FindChild(sp: Laya.Sprite3D, name: string) {if (sp.name == name) {return sp;} else {let target;let vObj;let i = sp._children.length;while (--i > -1) {vObj = sp._children[i];target = this.FindChild(vObj, name);if (target)return target;}}
}
15.数组乱序:
public static resetArr(arr) {var len = arr.length;for (var i = 0; i < len; i++) {var index = Math.floor(Math.random() * (len - i));var tem = arr[index];arr[index] = arr[len - i - 1];arr[len - i - 1] = tem;}return arr;
}
16.截取字符串长度常用函数:
//获取字符串长度
public static getLength = function (str) {return str.replace(/[\u0391-\uFFE5]/g, "aa").length; //先把中文替换成两个字节的英文,再计算长度
};/**
* 截取指定长度的字符串
*/
public static getLengthStr = function (str, length) {var tmp = str;while (this.getLength(tmp) > length) {tmp = tmp.substr(0, tmp.length - 1);}return tmp;
};
17.返回范围内的值: 限制取值范围
/**
* 返回范围内的值
*/
public static clamp = function (min, value, max) {return Math.max(min, Math.min(value, max));
};
18.在权重数组中随机一个index
//在权重数组中随机一个index
public static randomIndexByWeight = function (array, total) {if (!total) {total = 0;for (var i = 0; i < array.length; i++) {if (array[i] == 0) continue;total += array[i];}}var ran = this.intRange(0, total);var index = 0;for (; index < array.length; index++) {if (array[index] == 0) continue;ran -= array[index];if (ran <= 0)return index;}return 0;
};
19.数组元素反转:
(1) 方法一: reverse方法
var arr1 = ['a', 'b', 'c', 'd', 'e']
console.log('source arr1 =', arr1)
arr1.reverse()
console.log('target arr1 =', arr1)
(2) 方法二:元素交换位置
var arr = [1, 2, 3, 4, 5, 6]
console.log('source arr =', arr)
for (var i = 0; i < arr.length / 2; i++) {var temp = arr[i]arr[i] = arr[arr.length - 1 - i]arr[arr.length - 1 - i] = temp
}
console.log('target arr =', arr)
20.数组的随机函数:
/**
* 随机整数 [min, max)
* @param {最小值} min
* @param {最大值} max
*/
randomInt (min, max) {return Math.floor(Math.random() * (max - min) + min);
}/**
* 从数组中随机一个元素
* @param {数组} array
*/
arrayRandom (array) {var idx = this.randomInt(0, array.length);return array[idx];
}/**
* 从数组中随机一个元素并从数组中删除
* @param {数组} array
*/
shiftRandom (array) {var idx = this.randomInt(0, array.length);var value = array[idx];array.removeAt(idx);return value;
}