数组排序
var data = [{ name: "李世民", type: 1 }, { name: "刘备", type: 3 }, { name: "康熙", type: 2 }, { name: "曹操", type: 1 }, ] function compareUp(propertyName) { // 升序排序 if ((typeof data[0][propertyName]) != "number") { // 属性值为非数字 return function (object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; return value1.localeCompare(value2); //localeCompare 方法来实现中文按照拼音排序 } } else { return function (object1, object2) { // 属性值为数字 var value1 = object1[propertyName]; var value2 = object2[propertyName]; return value1 - value2; //val2-val1 降序 } } }console.log(data.sort(compareUp("type"))){name: "李世民", type: 1}1:{name: "曹操", type: 1}2:{name: "康熙", type: 2}3:{name: "刘备", type: 3}
//来源于 https://www.cnblogs.com/xiao-hong/p/3194027.html
//来源于 https://www.cnblogs.com/xiao-hong/p/3194027.html// 1 filter() //过滤掉小于 10 的数组元素:function isBigEnough(element, index, array) { return (element >= 10);}var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);console.log(filtered);//结果:[12, 5, 8, 130, 44].filter(isBigEnough) : 12, 130, 44//=====================================================// 2 map() 将所有的数组元素转换为大写:var strings = ["hello", "Array", "WORLD"];function makeUpperCase(v) { return v.toUpperCase();}var uppers = strings.map(makeUpperCase);console.log(uppers);//结果:["hello", "Array", "WORLD"].map(makeUpperCase) : HELLO, ARRAY, WORLD//=====================================================================// 3 some()function _isBigEnough(element, index, array) { return (element >= 10);}var passed1 = [2, 5, 8, 1, 4].some(_isBigEnough);// passed is falsevar passed2 = [12, 5, 8, 1, 4].some(_isBigEnough);console.log(passed1); // falseconsole.log(passed2); // true some 只要有满足 就是true//===============================================================//every();//测试是否所有数组元素都大于等于10:function isBigEnough_every(element, index, array) { return (element >= 10);}var passed3 = [12, 5, 8, 130, 44].every(isBigEnough_every);var passed4 = [12, 54, 18, 130, 44].every(isBigEnough_every);console.log(passed3); // falseconsole.log(passed4); // true //every 全部满足 才是 true//===============================================================//forEach()function printElt(element, index, array) { document.writeln("[" + index + "] is " + element + ""); console.log(index);}[2, 5, 9].forEach(printElt);
数组去重
var arr = [1,2,2,3,4] // 需要去重的数组var set = new Set(arr) // {1,2,3,4}var newArr = Array.from(set) // 再把set转变成arrayconsole.log(newArr) // [1,2,3,4]