数组小结

170 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

创建数组的几种方式

  1. 数组对象字面量
  2. new Array()
    只有一个参数的时候,其作为数组的长度。 这个是个坑点。
  3. Array.from
  4. Array.of 与new Array, Array的区别在于,只有一个参数时,是作为元素,而不是作为长度。
  5. Array.prototype.slice, Array.prototype.concat等等, 其他方法创建新数组

关心一下Array.of方法就行。

改变数组本身的方法

改变自身值的方法一共有9个, 这就意味着他们返回值不是新的数组。

  1. Array.pototype.pop
    返回的是被弹出的元素。

  2. Array.pototype.push
    返回的是修改后数组的长度。

  3. Array.pototype.shift
    返回的是头部被移除的元素。

  4. Array.pototype.unshift
    返回的是修改后数组的长度。

  5. Array.pototype.reverse
    返回的是修改后数组。

  6. Array.pototype.sort
    因为采用的是原地排序,数组本身被改变。 返回的是修改后数组。

  7. Array.pototype.splice
    返回的是被删除的元素。

  8. Array.pototype.copyWithin
    返回的是修改后数组。

const array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4))
// expected output: Array ["d", "b", "c", "d", "e"]
  1. Array.pototype.fill
    返回的是修改后数组。

妙用小结

filter(Boolean)过滤空值

var arr = [{name:"tom", age: 18}, { name: "pik"},undefined];

const newArr = arr.filter(Boolean)


// 打印Boolean
console.log(Boolean)
// ƒ Boolean() { [native code] }

Array.from生成随机数据或者序列

const createRandomValues = Array.from({length:10}, (v,i)=> Math.random());
// [0.25940121194082666, 0.8386585479250679, 0.26516411790325556, 0.6017479968140447, 
//0.5730002277371962, 0.8710995725057937, 0.18703989792580744, 
//0.7930248062519736, 0.4589973173040094, 0.2985306917392727]

const createRandomValues = (creator, length = 10) => Array.from({length}, creator);
const createRange = (start, stop, step) =>
createRandomValues((_, i) => start + (i * step), (stop - start) / step + 1)

createRange (1,100,3) // [1, 4, 7, 10]

Array.from或者slice数组浅拷贝

var arr = [{a:1}, {a:2}]
var arr2 = arr.slice(0);
var arr2 = Array.from(arr);

Array.prototype.filter + Set 数组去重,求交集,求差集

// 引用类型
function intersect(arr1, arr2, key){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val[key]))

    return arr2.filter(val=> {
        return map.has(val[key]);
    });
}


// 原始数据类型
function intersectBase(arr1, arr2){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val))

    return arr2.filter(val=> {
        return map.has(val);
    });
}

var arr1 = [{p:0}, {p:1}, {p:2}] 
var arr2 = [{p:3}, {p:2}, {p:1}]  
intersect(arr1, arr2, "p"); // [{p:2, p: 1}]

const arr1 = [0, 1, 2] 
const arr2 = [3, 2, 0] 
intersectBase(arr1,arr2 );

求交集

// 引用类型
function intersect(arr1, arr2, key){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val[key]))

    return arr2.filter(val=> {
        return map.has(val[key]);
    });
}


// 原始数据类型
function intersectBase(arr1, arr2){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val))

    return arr2.filter(val=> {
        return map.has(val);
    });
}

求差集

// 引用类型
function difference(arr1, arr2, key){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val[key]))

    return arr2.filter(val=> {
        return !map.has(val[key]);
    });
}


// 原始数据类型
function differenceBase(arr1, arr2){ 
    const map = new Map();
    arr1.forEach(val=> map.set(val))

    return arr2.filter(val=> {
        return !map.has(val);
    });
}

reduce处理queryString, compose函数, promise顺序执行

queryString:

 function getQueryString(){
     return location.search.slice(1)
        .split("&")
        .filter(Boolean)
        .reduce(function(obj, cur){
            var arr = cur.split("=");
            if(arr.length !=2){
                return obj;
            }
            obj[decodeURIComponent(arr[0])] = decodeURIComponent(arr[1]);
            return obj;               
        }, {})
 }
 

redux的代码:(compose)

 function compose(...funcs) {
  if (funcs.length === 0) {
    // infer the argument type so it is usable in inference down the line
    return (arg) => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce(
    (a, b) =>
      (...args) =>
        a(b(...args))
  )
}

promise顺序执行:(云的世界)

function runPromises(promiseCreators, initData) {
    return promiseCreators
        .reduce((promise, next) => promise
                .then((data) => next(data))
            , Promise.resolve(initData));
}

小结

今天你收获了吗?