JS数组方法join()用法实例分析-创新互联

本文实例讲述了JS数组方法join()用法。分享给大家供大家参考,具体如下:

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名申请、虚拟空间、营销软件、网站建设、邵阳网站维护、网站推广。

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;
}
// 不传任何值或者传入undefined
var arr = [1, 2, 3, 4, 5, 6];
console.log(arr.copyJoin()); // 1,2,3,4,5,6
console.log(arr.copyJoin().length); // 11
console.log(arr.copyJoin(undefined)); // 1,2,3,4,5,6
console.log(arr.copyJoin(undefined).length); // 11
// 传入参数
console.log(arr.copyJoin('||')); // 1||2||3||4||5||6
console.log(arr.copyJoin('||').length);  // 16
// 数组中的某一项是null或undefined
var arr2 = [1, undefined, 2, undefined, 3, 4, 5, 6, 7, null, 8, null, 9];
console.log(arr2.copyJoin()); // 1,,2,,3,4,5,6,7,,8,,9
console.log(arr2.copyJoin().length); // 21
console.log(arr2.copyJoin(undefined)); // 1,,2,,3,4,5,6,7,,8,,9
console.log(arr2.copyJoin(undefined).length); // 21

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站题目:JS数组方法join()用法实例分析-创新互联
当前URL:http://myzitong.com/article/ddgics.html