编程语言
首页 > 编程语言> > javascript – 包含回车符的拆分数组元素

javascript – 包含回车符的拆分数组元素

作者:互联网

从一个字符串数组开始,其中一些字符串具有回车功能:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

我想要做的是摆脱回车,将字符串拆分为与回车1一样多的元素:

["Saab","Volvo","BMW","Honda","Audi","Mazda"];

我得到了什么.split:

valArray.split("\n");
["Saab","Volvo",["BMW","Honda","Audi"],"Mazda"];

有什么建议?

解决方法:

在拆分回车符后将项目映射到数组,然后通过应用concat展平数组:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = [].concat.apply([], valArray.map(function(item) {
  var items = item.split('\n');
  
  return items;
}));

console.log(result);

另一种没有循环的方法:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = valArray.join(',').split('\n').join(',').split(',');

console.log(result);

标签:elements,javascript,arrays,split,carriage-return
来源: https://codeday.me/bug/20190828/1755347.html