美文网首页
JavaScript中Array数组的join用法

JavaScript中Array数组的join用法

作者: 仙姑本姑 | 来源:发表于2019-12-08 22:46 被阅读0次

join(),这个方法的功能就是:将array数据中每个元素都转为字符串,用自定义的连接符分割,如果 join()里面不加任何参数,用法与toString()一样

var num = Array("hello","word");
console.log(num.join());
console.log(num.join(""));
console.log(num.join("-"));
hello,word
helloword
hello-word

通过运行结果我们可知,join方法的参数代表的连接字符串的连接符,这里我们可以自定义。

拓展:通过该方法我们可以实现字符串的重复,将要重复的字符串作为连接符,那么连接长度为重复次数加一的空数组即可实现该方法,就像十棵树中间是有九个间隔,这里需要数组的长度加一。

下面将重复字符串写成函数:

function times(str,num){
    return new Array(num+1).join(str);
}
console.log(times("abc",3)); //输出结果为:abcabcabc

原文链接:https://blog.csdn.net/weixin_30363263/article/details/81145574

相关文章

网友评论

      本文标题:JavaScript中Array数组的join用法

      本文链接:https://www.haomeiwen.com/subject/lyyvgctx.html