js中join方法

js中的join方法

join方法用于把数组中的所有元素放入一个字符串。

元素是通过指定的分隔符进行分隔的。

大白话:join方法可以用符不同的分隔符来构建这个字串。join方法值接受一个参数,即用作分隔符的字符串,然后返回所有数组项的字符串。

var arr = ["red","yellow","blue"];
var array = [];

下面开始调用join方法

1

array = arr.join(undefined);
console.log(array);    

输出结果为: red,yellow,blue。

因为join方法的参数不传或者传入undefined会默认用逗号分隔。

2

array = arr.join("|");
console.log(array);    

输出结果为: red|yellow|blue。

join参数用是用"|"来分隔的

3

array = arr.join(" | ");
console.log(array);    

输出结果为: red | yellow | blue。

join参数使用" | "来分隔的,字符串是什么就用什么来分隔。

4

console.log(Array.isArray(array));  
console.log(typeof array);  

输出结果为:false   String

如果用join来分隔数组的话,这个变量就会变成字符串类型,就算之前是数组也会变成字符串类型。

​​​​​​​5

console.log(array.join(" | "));

输出结果报错: array.join is not a function

因为array现在已经变成了字符串了,而join只能数组来调用,所以报错!

解决方案!木有,我还不会...hhh

猜你喜欢

转载自blog.csdn.net/qq_41702660/article/details/81386965