数组和字符串的相互转换

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

 

posted @ 2017-02-03 15:42  花.花  阅读(300)  评论(0编辑  收藏  举报