JS-数组API

来源:互联网 发布:360剑雨江湖进阶数据 编辑:程序博客网 时间:2024/06/05 20:21

1、ES3数组方法

增加:(返回值为数组length)    push();    unshift():去除:(返回值为去除元素)    pop();    shift();插入、替换、删除:(slice方法返回新数组)    splice( start, num, docus );    参数:1、开始索引  2、个数 3、....添加元素    slice( start, end);   参数:1、开始索引  2、结束索引    (参数可以是负数) 翻转:    reverse();转换为字符串:    join( ' ' );合并数组:(返回新数组)    concat();排序:    sort();   数组排列,数组中对象的某属性排列        1. 默认按照UniCode编码来排序        2. 使用sort方法的回调函数来指定排序规则            * 定义回调函数的两个形参a , b            *             * a 相对于 b 位置在前            *             * 如果回调函数的返回值 大于 0,交换位置            *             * 如果返回值 小于 0 ,不交换位置            *             * 如果返回值 等于 0,保持相对位置            self.data.sort( function( a, b ) {                return a[ sortBy ] > b[ sortBy ] ? -sortKey : sortKey;            } );

2、ES5数组方法

forEach():    第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身        [].forEach(function(value, index, array) {            // ...        });    forEach除了接受一个必须的回调函数参数,还可以接受一个可选的上下文参数(第2个参数)        array.forEach(callback,[ thisObject])        var database = {          users: ["张含韵", "江一燕", "李小璐"],          sendEmail: function (user) {            if (this.isValidUser(user)) {              console.log("你好," + user);            } else {              console.log("抱歉,"+ user +",你不是本家人");              }          },          isValidUser: function (user) {            return /^张/.test(user);          }        };        // 给每个人法邮件        database.users.forEach(  // database.users中人遍历          database.sendEmail,    // 发送邮件          database               // 使用database代替上面标红的this        );    手动实现:foreach方法:        if (typeof Array.prototype.forEach != "function") {          Array.prototype.forEach = function (fn, context) {            for (var k = 0, length = this.length; k < length; k++) {              if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) {                fn.call(context, this[k], k, this);              }            }          };        }    注意:如果这第2个可选参数不指定,则使用全局对象代替(在浏览器是为window),严格模式下甚至是undefined
map():      是原数组被“映射”成对应新数组        [].map(function(value, index, array) {            // ...        });        var data = [1, 2, 3, 4];        var arrayOfSquares = data.map(function() {});    手动实现map方法:        if (typeof Array.prototype.map != "function") {          Array.prototype.map = function (fn, context) {            var arr = [];            if (typeof fn === "function") {              for (var k = 0, length = this.length; k < length; k++) {                       arr.push(fn.call(context, this[k], k, this));              }            }            return arr;          };        }
filter():返回值为新数组    array.filter(callback,[ thisObject]);
some():返回值为truefalse        array.some(callback,[ thisObject]);
every():返回值为truefalse        array.every(callback,[ thisObject]);

3、数组检测

Array.isArray(); [] instanceof ArrayObject.toString.call(  arr  ).slice(8,-1);arr.constructor;//Array
原创粉丝点击