我想检查unorderedPhrases
数组中的所有音频文件名是否在包含URL的result
数组中。如果都存在,则返回true
,如果存在,则返回false
。
这是我尝试过的。我不知道为什么它总是返回false
!?
let result = [
"https://example.com/test/unordered/i was sent to earth to protect you_A/i was sent.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to earth.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to protect you.mp3",
];
const unorderedPhrases = [
'i was sent',
'to earth',
'to protect you'
];
function checkResults(){
return unorderedPhrases.every(r=> result.includes(r));
}
console.log(checkResults())
上面的代码应该返回true,因为unorderedPhrases
中的所有音频文件都存在于result
数组中。
如果我们有此数组,则它应该返回false
,因为unorderedPhrases
中有一个项目在result
中不存在:
let result = [
"https://example.com/test/unordered/i was sent to earth to protect you_A/i was sent.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to earth.mp3",
];
答案 0 :(得分:3)
如果您想忽略文件夹结构而只考虑最后的内容,可以先从每个result
项目中删除文件夹部分,将其变成另一个数组,然后遍历短语,检查没有文件夹部分的数组是否包含短语加.mp3
:
let result = [
"https://example.com/test/unordered/i was sent to earth to protect you_A/i was sent.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to earth.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to protect you.mp3",
];
const resultWithoutFolders = result.map(str => str.split('/').pop());
const unorderedPhrases = [
'i was sent',
'to earth',
'to protect you'
];
function checkResults() {
return unorderedPhrases.every(
phrase => resultWithoutFolders.includes(phrase + '.mp3')
);
}
console.log(checkResults())
答案 1 :(得分:0)
由于result
是2D数组,因此返回false。这意味着您的result
具有3个元素,即这3个字符串,每个字符串都是由字符组成的数组。
编辑:很抱歉您的错误假设。 T.J.人群为我指出了。它不是二维数组。字符串也像数组一样。因此可以像二维数组一样访问它
这将是一个更正确的代码段:
let result = [
"https://example.com/test/unordered/i was sent to earth to protect you_A/i was sent.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to earth.mp3",
"https://example.com/test/unordered/i was sent to earth to protect you_A/to protect you.mp3",
];
const unorderedPhrases = [
'i was sent',
'to earth',
'to protect you'
];
function checkResults(){
return unorderedPhrases.every(r => result[0].includes(r))
}
console.log(checkResults())
如果要检查result
中的所有3个字符串,则必须对其进行循环。每次都像上面一样检查unorderedPhrases