javascript - 转换数组

时间:2015-08-07 05:39:17

标签: javascript arrays

如何使用Javascript打开此列表:

var array = ["no yes", "maybe certainly"];

进入这一个:

var array2 = ["no", "yes", "maybe", "certainly"]

3 个答案:

答案 0 :(得分:4)

如果数组元素中有多个空格的可能性,最好在这里使用regex

  1. 按空格加入数组元素
  2. 使用正则表达式从字符串中提取非空格字符
  3. var array = ["       no yes     ", "     maybe     certainly  "];
    
    var array2 = array.join('').match(/\S+/g);
    
    document.write(array2);
    console.log(array2);

答案 1 :(得分:1)

您可以join数组中的所有元素,然后split将其添加到数组中,就像这样



// var array = ["no yes", "maybe certainly"];
var array = ["no yes     ", "    maybe    certainly"];
var array2 = array.join('').trim().split(/\s+/g);

console.log(array2);




答案 2 :(得分:0)

var array = ["no yes", "maybe certainly"]

answer = converfunction(array);

function converfunction(array){
return array.toString().replace(',',' ' ).split(' ')
}