Array::slice() 选择数组的一部分,并返回新数组。
Array::join() 将数组的所有元素连接成一个字符串
String::concat() 连接两个或多个字符串。
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
' and ' + myArray[myArray.length - 1]));
//Hill M, Zhang F, Dong L, Wilkinson JS and Harris N
改变他们的顺序:
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
for(var i = 0; i < myArray.length; i++)
myArray[i] = myArray[i].replace(/^(\S+)\s+(.+)$/, '$2 $1');
console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
' and ' + myArray[myArray.length - 1]));
//M Hill, F Zhang, L Dong, JS Wilkinson and N Harris
如果你想知道str.replace(/^(\S+)\s+(.+)$/, '$2 $1');
/^(\S+)\s+(.+)$/ 是匹配以下字符串的正则表达式:
^ #starts with
\S+ #one or more non whitespace characters, followed by
\s+ #one or more whitespace characters, followed by
.+ #one or more characters
替换字符串中的$1 和$2 代表正则表达式中的第一组和第二组(括号中的子模式)。