如果我有两个数组
A = [ "B,C,D"
"W,F,G"
"M,S,E"
]
D = [E]
并且想要将D或G与E(我指的是每行中的第三个(进行比较,如果它们相等,可以为我显示所有行。每行中第三个是每行的一部分,我只想比较第三个如果相等,则表明该行具有相等的变量。我写了这个代码,但没有给我需要的回应:
for(var k=0 ; k<A.length ; k++){
if(A[k].split(",")[2] === E) {
finalSuccessServices = A;
console.log(finalSuccessServices );
}
如何改进我的代码以获得具有相等变量的行?
您可以使用find()
来获取匹配字符串,前提是您只有一个匹配项:
const A = [ "B,C,D",
"W,F,G",
"M,S,E"
];
const D = ['E'];
let result = A.find(str => str.split(',')[2] === D[0]);
console.log(result)
您可以过滤数组并查找includes
。
var array = ["B,C,D", "W,F,G", "M,S,E"],
pattern = ['E'],
result = array.filter(s => pattern.includes(s.split(',')[2]));
console.log(result);
如果您只需要第一个,请服用find
。
var array = ["B,C,D", "W,F,G", "M,S,E"],
pattern = ['E'],
result = array.find(s => pattern.includes(s.split(',')[2]));
console.log(result);
您可以使用函数filter
和函数includes
来选择数组D
中具有第三个字母的行。
let A = [ "B,C,D", "W,F,G", "M,S,E" ],
D = ["E"],
result = A.filter(s => {
let [,,C] = s.split(",");
return D.includes(C);
});
console.log(result);
- 使用
split
和析构函数获取第三个元素 - 比较第三个值和第一个值(来自数组D(
- 控制台日志并推送到finalSuccessServices数组
const A = ["B,C,D", "W,F,G", "M,S,E"];
const D = ["E"];
const [first] = D;
const finalSuccessServices = [];
A.forEach(line => {
const [,, third] = line.split(",");
if (third === first) {
console.log(line);
finalSuccessServices.push(line);
}
});
console.log("finalSuccessServices", finalSuccessServices);