我有一個這樣的陣列。如果陣列中的至少一個子字串具有我正在搜索的值,它應該通過。
Value1 = [
"Grape | 100 |Food Catering Service",
"Apple | 100,000m |Food Catering Service",
"Water Melon | 100,000m |Catering Service Outside",
"100,000m |Food Catering Service Outside
]
使用打字稿,我試圖確保至少如果陣列中的子字串存在值 Food。即使這個 arrat 中的第三個子串沒有食物,它仍然應該通過。
到目前為止我已經嘗試過的代碼但沒有完成這項作業。它只回傳陣列
export function arraySubstring (expected:string, ignoreCase?: boolean): Expectation<string[], string> {
return Expectation.that("test", expected,
async(actor: Actor, actual: string[]): Promise<boolean> ==> {
try {
for (const value of actual) {
if(ignoreCase) {
if (!value.toLowerCase().includes(expected.toLowerCase())) return
false;
} else {
if (!value.includes(expected)) return false;
}
}
return true;
})
}
const value2= await webActor.attemptsTo(Ensure.that("my expectation",
value1, arraySubstring ("Food")))
uj5u.com熱心網友回復:
您的代碼依賴于它的順序。如果回圈的第一個元素不包含“食物”,它將回傳 false。Return 陳述句總是退出函式。
我建議創建一個字串并使用 來檢查第一次出現的索引indexOf("food"),類似的東西。
const array = [
"Grape | 100 |Food Catering Service",
"Apple | 100,000m |Food Catering Service",
"Water Melon | 100,000m |Catering Service Outside",
"100,000m |Food Catering Service Outside",
];
const found = array
.reduce((obj, entry) => obj.concat(entry))
.toLocaleLowerCase()
.indexOf("food");
if (found >= 0) {
console.log("Array contains food");
} else {
console.log("Array does not contain food");
}
如果你想迭代你需要回傳真實的情況,這將從你的代碼中洗掉順序的重要性。
const array = [
"Grape | 100 |Food Catering Service",
"Apple | 100,000m |Food Catering Service",
"Water Melon | 100,000m |Catering Service Outside",
"100,000m |Food Catering Service Outside",
];
const ignoreCase = true;
const expected = "Food";
const containsExptected = (_array) => {
for (const value of _array) {
if (ignoreCase) {
if (value.toLowerCase().indexOf(expected.toLowerCase()) >= 0) return true
} else {
if (value.indexOf(expected) >= 0) return true;
}
}
return false;
};
const found = containsExptected(array);
if (found) {
console.log("Array contains food");
} else {
console.log("Array does not contain food");
}
uj5u.com熱心網友回復:
這是檢查字串陣列中子字串匹配的單行代碼:
const value = ["Grape | 100 |Food Catering Service", "Apple | 100,000m |Food Catering Service", "Water Melon | 100,000m |Catering Service Outside", "100,000m |Food Catering Service Outside"]
const expected = "Food"
const ignoreCase = true
console.log(value.some(val => (ignoreCase ? val.toLowerCase().includes(expected.toLowerCase()) : val.includes(expected))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389474.html
標籤:javascript 数组 打字稿
