数组方法实现(一)————数组方法join()

来源:互联网 发布:科比布莱恩特生涯数据 编辑:程序博客网 时间:2024/05/29 15:06

join()方法

  1. 定义和用法:
    join() 方法用于把数组中的所有元素放入一个字符串。
    元素是通过指定的分隔符进行分隔的。
  2. 语法:arrayObject.join(separator)
  3. 参数:可选,指定要使用的分隔符。
    注:不给join()方法传入任何值,或者给它传入undefined,则使用逗号作为分隔符。
    IE7及更早版本会错误的使用字符串“undefined”作为分隔符。
    数组中的某一项是null或undefined,那么该值在join()、toLocaleString()、toString()和valueOf()方法返回的结果中以空字符串表示。
  4. 返回值:
    返回包含所有数组项的字符串。

代码如下:

Array.prototype.copyJoin = function() {    var string = '';    for(var i = 0; i < this.length; i++) {        // 将数组中各项值为null 或undefined的项改为空字符串。        if(this[i] == null || this[i] == undefined) {            this[i] = '';        }        // 对数组进行操作        if(arguments.length == 1 && arguments[0] != undefined) { //指定使用的分隔符            string += (i < this.length - 1) ? this[i]  + arguments[0] : this[i];        }        else { // 默认使用的分隔符————逗号            // if(i < this.length - 1) {            //     string += this[i] + ',';            // }            // else {            //     string += this[i];            // }            string += (i < this.length - 1) ? this[i] + ',' : this[i];        }                }    return string;}// 不传任何值或者传入undefinedvar arr = [1, 2, 3, 4, 5, 6];arr.copyJoin(); // 1,2,3,4,5,6arr.copyJoin().length; // 11arr.copyJoin(undefined); // 1,2,3,4,5,6arr.copyJoin(undefined).length; // 11// 传入参数arr.copyJoin('||'); // 1||2||3||4||5||6arr.copyJoin('||').length;   // 16// 数组中的某一项是null或undefinedvar arr2 = [1, undefined, 2, undefined, 3, 4, 5, 6, 7, null, 8, null, 9];arr2.copyJoin();  // 1,,2,,3,4,5,6,7,,8,,9arr2.copyJoin().length; // 21arr2.copyJoin(undefined); // 1,,2,,3,4,5,6,7,,8,,9arr2.copyJoin(undefined).length;  // 21

以上在IE8+ join()方法一样,但是在IE7及更早版本(copyJoin()方法不存在):

arr.join(undefined));  // 1undefined2undefined3undefined4undefined5undefined6arr.join(undefined).length); // 51arr2.join(undefined)); //  1undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9arr2.join(undefined).length);  //  117
阅读全文
0 0