JavaScript中join()方法如何使用

发布时间:2021-08-12 16:03:33 作者:Leah
来源:亿速云 阅读:344

这期内容当中小编将会给大家带来有关JavaScript中join()方法如何使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

join()方法

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

代码如下:

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

运行结果:

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

arr.join(undefined)); // 1undefined2undefined3undefined4undefined5undefined6arr.join(undefined).length); // 51arr2.join(undefined)); // 1undefinedundefined2undefinedundefined3undefined4undefined5undefined6undefined7undefinedundefined8undefinedundefined9arr2.join(undefined).length); // 117

上述就是小编为大家分享的JavaScript中join()方法如何使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么对.Net与JavaScript的时间日期格式进行转换
  2. javascript中怎么判断是否手机访问

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript join()

上一篇:JavaScript中reverse()方法如何使用

下一篇:JavaScript中怎样遍历数组

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》