Skip to content

Array 对象方法整理 #5

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
phoebeCodeSpace opened this issue Jun 17, 2017 · 5 comments
Open

Array 对象方法整理 #5

phoebeCodeSpace opened this issue Jun 17, 2017 · 5 comments
Labels

Comments

@phoebeCodeSpace
Copy link
Owner

phoebeCodeSpace commented Jun 17, 2017

数组创建与修改

1. 创建
  • var arr = [];
  • var arr = new Array()
  • Array.of(el1[,el2[...]]) //创建一个新数组实例
  • Array.from(arrayLike) //将类数组(类似数组的对象和可遍历的对象)转为真正的数组。
    // ES5的写法
    var arr1 = [].slice.call(arrayLike);
    // ES6的写法
    let arr2 = Array.from(arrayLike);
    
2. 合并
  • Array.prototype.concat(arr1[,arr2..]) //合并两个或多个数组。不更改现有数组,而是返回一个新数组。
3. 转化为字符串
  • Array.prototype.join(separator) //以separator(默认为逗号)拼接为字符串。
  • Array.prototype.toString() //把数组转换为字符串,数组中的元素之间用逗号分隔。

字符串转化为数组:s.split(","); //在每个逗号(,)处进行分解。

4. 填充
  • Array.prototype.fill(value[, start, end]) //用一个固定值填充[start,end)的元素。

判断数组

  • Array.isArray() //判断传递的值是否是一个 Array。

筛选排序递归

1. 筛选
  • Array.prototype.filter()
  • Array.prototype.map()
2. 排序
  • Array.prototype.reverse() //将数组中元素的位置颠倒。
  • Array.prototype.sort()
3. 递归
  • Array.prototype.reduce()

语法:arr.reduce(callback,[initialValue])

  • callback(accumulator,currentValue,currentIndex,array)
    • accumulator 上一次调用回调返回的值
    • currentValue 数组中正在处理的元素
    • currentIndex 数据中正在处理的元素索引
    • array 调用 reduce 的数组
  • initialValue [可选],用于第一次调用 callback 的第一个参数。

增删改查

1. 查找
  • Array.prototype.some(callback) //执行一次 callback 函数,直到找到一个使得 callback 返回true。
  • Array.prototype.every(callback) //数组的所有元素是否都通过callback 函数。
  • Array.prototype.find(callback) //在数组中返回符合callback第一个元素的值。
  • Array.prototype.findIndex(callback)//返回数组中满足callback的第一个元素的索引。否则返回-1。
  • Array.prototype.includes(searchElement) //是否包含一个指定的值
2. 增、删
  • Array.prototype.pop() //删除数组最后一个元素,并返回该元素的值。
  • Array.prototype.push() //增加元素到数组末尾。
  • Array.prototype.shift() //删除数组第一个元素。
  • Array.prototype.unshift() //增加元素到数组开头。
  • Array.prototype.slice(start,end) //返回[start,end)**浅拷贝**到一个新数组对象,**原数组不会被修改**。
  • Array.prototype.splice() //通过删除现有元素和/或添加新元素来更改一个数组的内容,**会直接对数组进行修改**。
    • array.splice(start)
    • array.splice(start, deleteCount)
    • array.splice(start, deleteCount, item1, item2, ...)

    start : 如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从1计数)。
    deleteCount : 如果 deleteCount 是 0,则不移除元素,这种情况下,至少应添加一个新元素;如果 deleteCount 大于start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位);如果deleteCount被省略,则其相当于(arr.length - start)。
    item1, item2, ... :要添加进数组的元素

循环遍历

  • Array.prototype.map(callback)
  • Array.prototype.forEach(callback)
  • Array.prototype.entries() //返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
  • Array.prototype.keys() //返回一个新的Array迭代器,它包含数组中每个索引的键。
  • Array.prototype.values() //返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值。
      for (let index of ['a', 'b'].keys()) {    //遍历键
        console.log(index);
      }
      // 0
      // 1
    
      for (let elem of ['a', 'b'].values()) {   //遍历值
        console.log(elem);
      }
      // 'a'
      // 'b'
    
      for (let [index, elem] of ['a', 'b'].entries()) {   //遍历键/值对
        console.log(index, elem);
      }
      // 0 "a"
      // 1 "b"
    

实用方法:

将参数转化为数组

var _arguments=Array.prototype.slice.apply(arguments)

参考文档

@phoebeCodeSpace phoebeCodeSpace changed the title Array 对象方法 Array 对象方法整理 Jun 17, 2017
@phoebeCodeSpace
Copy link
Owner Author

phoebeCodeSpace commented Oct 18, 2017

数组的深拷贝

  1. arr.slice
var arr = [1,2,3,4,5]
var arr2 = arr.slice(0)
arr[2] = 5
console.log(arr)
console.log(arr2)

参考:

http://blog.csdn.net/fungleo/article/details/54931379

@phoebeCodeSpace
Copy link
Owner Author

数组去重

  1. ES6
[...new Set([2,"12",2,12,1,2,1,6,12,13,6])]
//[2, "12", 12, 1, 6, 13]
  1. ES5 filter
    indexOf返回数组元素第一个位置。
[1,2,3,1,'a',1,'a'].filter(function(ele,index,array){
    return index===array.indexOf(ele)
})
  1. 新数组保存
  • 创建一个新的数组存放结果
  • 创建一个空对象
  • for循环时,每次取出一个元素与对象进行对比,如果这个元素不重复,则把它存放到结果数组中,同时把这个元素的内容作为对象的一个属性,并赋值为1,存入到第2步建立的对象中。
/*
  使用方法:
  var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
  alert(arr.unique3());
*/

Array.prototype.unique = function(){
 var res = [];
 var json = {};
 for(var i = 0; i < this.length; i++){
  if(!json[this[i]]){
   res.push(this[i]);
   json[this[i]] = 1;
  }
 }
 return res;
}

@phoebeCodeSpace
Copy link
Owner Author

phoebeCodeSpace commented Oct 24, 2017

排序

数据按中文拼音首字母排序

var seatlist = [{id:1,name:'张三'},{id:2,name:'李四'},{id:3,name:'王五'}]
seatlist.sort((a,b)=>{
   return a.name.localeCompare(b.name, 'zh-Hans-CN', {sensitivity: 'accent'})
})

表格实现正序反序

arr.sort((a,b)=>{
   let flag = (Number(a) - Number(b)>=0 ? -1 : 1;
   if(sort==2){
     return flag;
   }else{
     return -flag;
   }
})

@phoebeCodeSpace
Copy link
Owner Author

    var obj={};
    var chinese=[], // 汉字
        english=[], // 字母
        special=[], // 特殊字符
        number=[];  // 数字

    //判断类型
    function chenkType(data) {
        const reNum = /^[0-9]/;                 // 数字校验规则
        const reEn = /^[a-zA-Z]/;               // 字母校验规则
        const reCh = /[^\u0000-\u00FF]/;        // 中文校验
        const type = {
            number: reNum,
            chinese: reCh,
            english: reEn
        }
        for (let d of data) {
            if (reNum.test(d)) {
                number.push(d);
            } else if (reEn.test(d)) {
                english.push(d);
            } else if (reCh.test(d)) {
                chinese.push(d);
            } else {
                special.push(d);
            }
        }
    }
    //汉字排序
    function pySegSort(arr) {
        var letters = "*abcdefghjklmnopqrstwxyz".split('');
        var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');

        var segs = [];
        var curr;

        letters.forEach((letter,i)=>{
                curr = {letter, data:[]};  // 当前字母,对应数据
                arr.forEach((word)=>{
                if((!zh[i-1] || zh[i-1].localeCompare(word,"zh") <=0 ) && word.localeCompare(zh[i], "zh")==- 1) {
                        curr.data.push(word);
                    }
                })
                if(curr.data.length) {
                    segs.push(curr);
                    curr.data.sort((a,b)=>{a.localeCompare(b,"zh")});
                }
        });
        return segs;
    }


   //排序
    function sortAll(data) {
        // 类型归类
        chenkType(data);

        var temphanzi=pySegSort(chinese);
        var arr1 = [].concat(english,temphanzi)
            arr1.sort((a,b)=>{
                let c = a.letter || a,
                    d = b.letter || b;
                return c.localeCompare(d)
            })
        var arr2 = number;
            arr2.sort((a,b)=>{
                return a-b>0
            })
        var arr3 = special.sort((a,b)=>{
                return a.localeCompare(b)
        })
        var arr = arr1.concat(arr2,arr3);
        var result = [];
        arr.map((item)=>{
            result.push(item.data || item);
        })
        return result.reduce((previous, current) => previous.concat(current))
   };

console.log(sortAll(['amy','Amy','艾米','123','bubu','748','##','%^','李四','-##^','张三','赵亮']));
// ["艾米", "amy", "Amy", "bubu", "李四", "张三", "赵亮", "123", "748", "-##^", "##", "%^"]

@phoebeCodeSpace
Copy link
Owner Author

数组求最大最小值

function maxArr(arr){
    return Math.max.apply(null,arr);
}
function minArr(arr){
    return Math.min.apply(null,arr);
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant