首页 > 代码库 > 数组和字符串的相互转换

数组和字符串的相互转换

1.字符串变成数组,split

var str = "1,2,3,4";

str.split(","); // ["1","2","3","4"]
str.split(); // ["1,2,3,4"]

 

2.数组变字符串,join

var arr = [1,2,3,4]
arr.join(); // "1,2,3,4"
arr.join(""); // "1234"
arr.join(" + "); // "1 + 2 + 3 + 4"

 

 

玩个有点好玩的,将数组里面的数字求和

 

function sum(arr){
  var str = arr.join(" + ");
  return eval(str);    
}
var arr = [1,2,3,4];
sum(arr) // 10

 

数组和字符串的相互转换