js數組 es6

數組排序html

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://juejin.im/post/5a0c16d16fb9a0450b65edad?utm_source=gold_browser_extension數組

//來源於 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 false
var passed2 = [12, 5, 8, 1, 4].some(_isBigEnough);
console.log(passed1); // false
console.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);  // false
console.log(passed4);  // true  //every 所有知足 纔是 true

//===============================================================
//forEach()
function printElt(element, index, array) {
    document.writeln("[" + index + "] is " + element + "<br />");
    console.log(index);
}
[2, 5, 9].forEach(printElt);

 

 

數組去重post

var arr = [1,2,2,3,4] // 須要去重的數組

var set = new Set(arr) // {1,2,3,4}
var newArr = Array.from(set) // 再把set轉變成array

console.log(newArr) // [1,2,3,4]
相關文章
相關標籤/搜索