JS数组操作

1.map

var arr = [1,2,3,4,5,6];
//第一个参数是元素,i是数组下标
arr = arr.map(function(item,i){
    return i +3;
});
//[ 3, 4, 5, 6, 7, 8 ]
console.log(arr);

另外:

var arr = [{start:10,end:199,type:"byte"},                   {start:100,end:400,type:"byte2"}];
arr = arr.map(function(range,index){
    return {
        start: range.start,
        end: range.end,
        index: index
   }
});
// [  
//    { start: 10, end: 199, index: 0 },
//    { start: 100, end: 400, index: 1 } 
// ]
console.log(arr);

看下面的例子:

function quoteCount(string) {
  var count = 0;
  var index = 0;

  while ((index = string.indexOf('"', index)) !== -1) {
    count++;
    index++;
  }

  return count;
}

function splitMediaTypes(accept) {
  var accepts = accept.split(',');

  for (var i = 1, j = 0; i < accepts.length; i++) {
    if (quoteCount(accepts[j]) % 2 == 0) {
      accepts[++j] = accepts[i];
    } else {
      accepts[j] += ',' + accepts[i];
    }
  }

  // trim accepts
  accepts.length = j + 1;

  return accepts;
}

2.filter 

var arr = [1,2,3,4,5,6];
//过滤掉i<=3的元素。
arr = arr.filter(function(i){
    return i >3;
});
//[ 4, 5, 6 ]
console.log(arr);
//ES6对数组有个includes处理,可以结合filter来过滤。

3.容易看错的代码

var val = false; 
var x = val || [];
console.log(x);
//[]

还有:

var arr = [1,2,3,4,5,6];
arr.type="array";
//[ 1, 2, 3, 4, 5, 6, type: 'array' ]
console.log(arr);

 4.sort

var arr = [1,8,3,9,4,5,6];
arr.sort(function(a,b){return a > b});

//[ 1, 3, 4, 5, 6, 8, 9 ]
console.log(arr); 
var arr = [{start:10,end:199,type:"byte"},{start:500,end:400,type:"byte2"},{start:200,end:499,type:"type3"}];
arr = arr.sort(
    function sortByRangeStart (a, b) {
          return a.start - b.start
})
//[ { start: 10, end: 199, type: 'byte' },
// { start: 200, end: 499, type: 'type3' },
//  { start: 500, end: 400, type: 'byte2' } ]
console.log(arr);

5.some(every)返回的都是false,true。

JavaScript数组some()方法测试数组中的某个元素是否通过由提供的功能来实现测试。

var arr = [4,5,6,8];
console.log(arr.some(function(item,i,arr){
    return item >= 8;
//true
}));

与some对应的是every函数,检测数组 ages 的所有元素是否都大于 18,代码如下:

  var ages = [32, 33, 16, 40];
  function checkAdult(age) {
    return age >= 18;
  }
  var res = ages.every(checkAdult);
  //false
  console.log(res);

6.find

var  arr=[
    {
        id: 1,
        name: 'a'
    },
    {
        id: 2,
        name: 'b'
    },
]


var obj=arr.find(function (x) {
    return x.id === 1
})
alert(obj.name);

7.套路(对数组每个元素重新处理,形成一个新的数组)

//accepts[i]依次处理,循环内i与j不重合,而且j<=i。形成新的数组,这个数组是脱胎于accepts,
for (var i = 0, j = 0; i < accepts.length; i++) {
    var mediaType = dealArray(accepts[i].trim(), i);
    //如果存在,则accepts[j]重新赋值
    if (mediaType) {
      accepts[j++] = mediaType;
    }
  }
  // trim accepts,封死其他多余无用的值。
  accepts.length = j;
  return accepts;

 遍历数组时还有一种变异,这样:

for (var i = 1, j = 0; i < accepts.length; i++) {
   //accepts[j]的形成与其他元素有密切关系。
    if (flag) {
      accepts[++j] = accepts[i];
    } else {
      accepts[j] += ',' + accepts[i];
    }
  }

 8.splice() 方法

 向/从数组中添加/删除项目,然后返回被删除的项目:

var args = ["4","6","8","10","12"];
//从args[3](含)开始删除1个元素。
var index  = 3;
args.splice(index, 1);
//args=4,6,8,12
console.log("args="+args);

9.shift方法

 var xx = [1,2,3,4,5];
 //1
 console.log(xx.shift());
 //[ 2, 3, 4, 5 ]
 console.log(xx);

另外还有unshift,向数组添加一个元素。 

10.forEach方法

  ES5新增对数组的操作

var obj = {
   x:"x1",
   y:"y1"
};
//ES5语法,x,y
console.log(Object.keys(obj)); 
var obj = {
    x:"x1", 
    y:"y1"
};
Object.keys(obj).forEach(function(ele,index){
     console.log("ele=",ele);
     console.log("index=",index);
});
// ele= x
// index= 0
// ele= y
// index= 1

注意:forEach()无法在所有元素都传递给调用的函数之前终止遍历。也就是说,没有像for循环中使用的相应的break语句。如果要提前终止,必须把forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止。 

11. reduce方法

// vue源码, 可以把数组元素累计执行下去形成一个结果,然后又和下一个进行运行,最终形成一个汇总的结果。
function genStaticKeys (modules) {
  return modules.reduce((keys, m) => {
    return keys.concat(m.staticKeys || [])
  }, []).join(',')
}
var modules = [{staticKeys: ['staticClass'], transformNode:1, genData:2},
    { preTransformNode:3 }, 
    { staticKeys: ['staticClass'],transformNode:1,genData:2}];
console.log(genStaticKeys(modules));
// staticClass,staticClass

 12. concat

合并数组:

console.log(['a'].concat(['b'])) //['a', 'b']

与下面的代码一样:

console.log(['a'].concat('b'))

下面是一些开源包对数组或者对象的高级处理:

// express-winston-master源码
function
filterObject(originalObj, whiteList, initialFilter) { var obj = {}; var fieldsSet = false; [].concat(whiteList).forEach(function (propName) { var value = initialFilter(originalObj, propName); if(typeof (value) !== 'undefined') { obj[propName] = value; fieldsSet = true; }; }); return fieldsSet?obj:undefined; } /* 形成value。 */ options.requestFilter = options.requestFilter || function (req, propName) { return req[propName]; }; /* 返回undefined或者对象,这个对象是从req.body中过滤出来的,过滤的key数组为whitelist,requestFilter是通过key对value处理函数 */ filteredBody = filterObject(req.body, whitelist, options.requestFilter);

 另外,还有打平数组:

var a = ['a', 'b', 'c',['e', 'f'], 'g']
console.log(Array.prototype.concat.apply([], a))
//[ 'a', 'b', 'c', 'e', 'f', 'g' ]
原文地址:https://www.cnblogs.com/liuyinlei/p/6895127.html