进行DNA挑战并且如此接近但明显误解prototype.split("")
。将这些字符串["AC", "CA", "TA"]
转换为子数组的最佳方法是什么? [["A","C"]["C","A"]["T","A"]]
function pairElement(str) {
//break into array
var arr = str.split("");
//add new letter (could be refactored as switch)
for (i = 0; i < arr.length; i++) {
if (arr[i] == "G") {
arr[i] += "C";
} else if (arr[i] == "C") {
arr[i] += "G";
} else if (arr[i] == "T") {
arr[i] += "A";
} else if (arr[i] == "A") {
arr[i] += "T";
}
}
//break into arrays again
//this is how I'm trying to use.split to break it up. Doesn't work.
var broken = [];
for (x = 0; x < arr.length; x++) {
broken += arr[x].split("");
}
//return
return arr;
}
console.log(pairElement("GCG"));
&#13;
答案 0 :(得分:3)
您可以""
.map
和split
var o = ["AC", "CA", "TA"];
var s = o.map(e=> e.split(""));
console.log(s)
&#13;
答案 1 :(得分:2)
你实际上只需将拆分结果推送到损坏的数组中并返回它!
function pairElement(str) {
//break into array
var arr = str.split("");
//add new letter (could be refactored as switch)
for (i = 0; i < arr.length; i++) {
if (arr[i] == "G") {
arr[i] += "C";
} else if (arr[i] == "C") {
arr[i] += "G";
} else if (arr[i] == "T") {
arr[i] += "A";
} else if (arr[i] == "A") {
arr[i] += "T";
}
}
//break into arrays again
//this is how I'm trying to use.split to break it up. Doesn't work.
var broken = [];
for (x = 0; x < arr.length; x++) {
broken.push(arr[x].split(""));
}
//return
return broken;
}
console.log(pairElement("GCG"));
&#13;
答案 2 :(得分:1)
回答你的最佳方式&#39;问题,将您的数组映射到他们自己的拆分版本:
{{1}}
答案 3 :(得分:1)
功能风格非常简单:
> seq = ['AC', 'CA', 'TA']
[ 'AC', 'CA', 'TA' ]
> seq.map(s => s.split(''))
[ [ 'A', 'C' ], [ 'C', 'A' ], [ 'T', 'A' ] ]
答案 4 :(得分:1)
总的来说,我会对整个功能进行一些重构:
var m = new Map([["G", "C"], ["C", "G"], ["A", "T"], ["T", "A"]]);
function pairElement(str) {
return [...str].map(c => [c, m.get(c)]);
}
console.log(pairElement("GCG"));
如果确保子阵列 从不 变异,那么您可以通过重复使用数组而不是一遍又一遍地创建它来节省大量内存
var m = new Map([["G", ["G", "C"]], ["C", ["C", "G"]], ["A", ["A", "T"]], ["T", ["T", "A"]]]);
function pairElement(str) {
return [...str].map(c => m.get(c));
}
console.log(pairElement("GCG"));
但是要直接回答您的问题,您可以在没有明确的.split()
调用的情况下执行此操作。既然你知道总有两个字符,你可以在字符串上使用参数解构。
var arr = ["AC", "CA", "TA"];
var s = arr.map(([a, b]) => [a, b]);
console.log(s)
使用rest语法甚至更短一点,如下所示:
var arr = ["AC", "CA", "TA"];
var s = arr.map(([...a]) => a);
console.log(s)
或者在数组文字中使用扩展语法:
var arr = ["AC", "CA", "TA"];
var s = arr.map(s => [...s]);
console.log(s)