跳至主要內容

数组

chanchaw大约 4 分钟javascript

字符串json转数组

下面第一行代码的文本手动填写到 UItext 中时没有外部的单引号

const fields='[["goodsId","goods_id"],["goodsName","goods_name"]]';
const fieldsArray = new Function('return ' + fields)();
console.log(fieldsArray);

未知类型转换为数组

const arr1 = Array.from(arr0);
const arr1 = [...arr0]

// 使用 slice 方法
var toArray = function(s){
    //try语句允许我们定义在执行时进行错误测试的代码块。
   //catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。
    try{
        return Array.prototype.slice.call(s);
    } catch(e){
        var arr = [];
        for(var i = 0,len = s.length; i < len; i++){
            //arr.push(s[i]);
               arr[i] = s[i];  //据说这样比push快
        }
         return arr;
    }
}

下一个兄弟元素

/**
 * 获取给定元素的下一个元素,如果currentItem=null则返回第一个元素
 * 如果没有下一个则返回上一个
 * @param {*} arr 数组对象
 * @param {*} currentValue 遍历数组时对比每个元素的字段 keyField 的值 == currentValue
 * @param {*} keyField 可鉴定唯一元素的字段名称
 */
export function getBrotherInObjArray8Val(arr, currentValue, keyField){
  if(!arr) return null;
  const arrObject = Array.from(arr);
  if(cancelAnimationFrame.length <=0) return null;
  if(!currentValue) return arrObject[0];

  for(let i=0;i<arr.length;i++){
    if(arr[i][keyField] === currentValue) {
      if( i+1 >= arr.length )
        if( i-1 < 0 )
          return arr[0];
        else
          return arr[i-1];
      else
        return arr[i+1];
    }
  }

  return null;
}

reduce 汇总

const arr=[1,2,3]
const sum = arr.reduce((pre,curr)=>pre+curr,0)
console.log(sum)

判断是否为空

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true

元素去重

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

// 下面是对象数组根据指定属性去重
/**
 * 获取对象数组指定字段去重数据构成的数组
 * @param arr 对象构成的数组
 * @param fieldName 对象中的字段
 * @returns {any[]}
 */
export function getDistFieldValArray(arr, fieldName){
  const arr01 = arr.map(item => item[fieldName])
  return Array.from(new Set(arr01))
}

追加元素

// push
arr.push('aa');

// splice
const arr = [1,2,3,4];
// 参数介绍:
// 第一个:要操作的位序
// 第二个:从该位序要删除的元素的个数
// 第三个:要追加的元素
// 由于下面的方法第二个参数设置了0表示不删除元素只追加
arr.splice(4,0,5);
console.log(arr);// 输出结果:1,2,3,4,5

// 通过下标
arr[arr.length] = 23

// concat
[1,2,3].concat(5,6,7);

// 通过展开运算符
[1,...[2,3,4],11,12]

遍历

// 序号遍历
for (let i = 0; i < arr.length; i++) {
    
}

// 使用 in 遍历
var a = [1, 2, 3];
for (var key in a) {
  console.log(a[key]);
}

// of
var arr = ['a','b','c'];
for(let item of arr) {
  console.log(item);
}

// forEach
const info = [
  {id: 1000, name: 'zhangsan'},
  {id: 1001, name: 'lisi'},
  {id: 1002, name: 'wangwu'}
]
arr.forEach( function(item) {
  console.log(item.id + '---' + item.name);
})
// 或者下面的写法,上下两种写法都会修改数组内元素的值
dataList.forEach(item => {
	item.kilo = item.kilogram;
	item.meter = item.planMeter;
})

排序

对象数组按照单属性排序

function compareFun(property){
    let order = 1;
    if(property[0] === '-'){
        order = -1;
        property = property.substr(1);
    }

    return function (a,b){
        const result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0
        return result * order;
    }
}

function testCompareFun(){
    const arrData = [
        {name: 'tom4', mdate: '202012',id:3},
        {name:'tom2', mdate:'202001',id:4},
        {name: 'tom1', mdate: '202008',id:1},
        {name: 'tom3', mdate: '202005',id:2}
    ]
    // 属性前面带有减号表示倒序排列,没有则表示正序排列
    // 排序函数 compareFun 只能根据一个属性进行排序
    const newArr = arrData.sort(compareFun('-id'));
    console.log(newArr);
}

对象数组按照多属性排序

function sortOneProp(property){
    let order = 1;
    if(property[0] === '-'){
        order = -1;
        property = property.substr(1);
    }

    return function (a,b){
        const result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0
        return result * order;
    }
}

// 按照多个属性进行排序
function sortMultiProps(){
    /*
        * 保存arguments对象,因为它将被覆盖
        * 注意arguments对象是一个类似数组的对象
        * 由要排序的属性的名称组成
        */
    let props = arguments
    return function (obj1, obj2) {
        let i = 0, result = 0, numberOfProperties = props.length
        // 从0开始获取不同的结果,因为有多个属性需要比较
        while(result === 0 && i < numberOfProperties) {
            result = sortOneProp(props[i])(obj1, obj2)
            i++
        }
        return result
    }
}
	
function testCompareFun(){
    const arrData = [
        {name: 'tom4', mdate: '202012',id:3},
        {name:'tom2', mdate:'202001',id:3},
        {name: 'tom1', mdate: '202008',id:1},
        {name: 'tom3', mdate: '202005',id:2}
    ]
    // 属性前面带有减号表示倒序排列,没有则表示正序排列
    // 排序函数 sortOneProp 只能根据一个属性进行排序
    //const newArr = arrData.sort(sortOneProp('-id'));
    //console.log(newArr);
    
    // 按照多个属性排序
    const newArr = arrData.sort(sortMultiProps('id','name'));
    console.log(newArr);
}