我试图分离并将一个数组的所有单词推送到另一个数组中。
旧数组:
["black cat", "white dog", "grey mouse"]
预期数组:
["black"],["cat"],["white"],["dog"],["grey"],["mouse"]
使用我的代码,我仍然用逗号分隔我的3个数组:
var arr = ["black cat", "white dog", "grey mouse"];
var arr_new = [];
for (i = 0; i < arr.length; i++) {
curr_val = arr[i].split(" ");
arr_new.push(curr_val);
}
答案 0 :(得分:3)
这是因为方法split
返回一个数组,其中的单词是用空格分割的。解决方案是迭代这个新数组而不是数组中的insert(push)。
var arr = ["black cat", "white dog", "grey mouse"];
var arr_new = [];
for (i = 0; i < arr.length; i++) {
curr_val = arr[i].split(" ");
for(j=0; j<curr_val.length;j++){
arr_new.push(curr_val[j]);
}
}
答案 1 :(得分:2)
我就是这样做的:
var oldArr = ["black cat", "white dog", "grey mouse"];
var newArr = oldArr
// this will turn each string into an Array of Arrays, like this:
// [["black", "cat"], ["white", "dog"], ["grey", "mouse"]]
.map(function(item) {
return item.split(" ");
})
// then, flatten this Array of Arrays into a single-level Array.
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Flatten_an_array_of_arrays
.reduce(function(a, b) {
return a.concat(b);
}, []);
document.writeln(JSON.stringify(newArr))
答案 2 :(得分:1)
JSFiddle:https://jsfiddle.net/6hLazr5w/1/
var newArray=[],
oldArray = ["black cat", "white dog", "grey mouse"];
for(item in oldArray) {
tmpArray = oldArray[item].split(' ');
for(tmp in tmpArray) {
newArray.push(tmpArray[tmp]);
}
}
答案 3 :(得分:1)
这里有一个减少&amp; amp;的选项替换方法,
var a = ["black cat", "white dog", "grey mouse"]
var re = a.reduce((acc,x)=>{
x.replace(/[a-zA-z]+/g,function(m){
acc.push([m])
});
return acc;
},[])
console.log(re)
&#13;