我想在文本陣列中搜索,并在文本中找到條目陣列的這個元素之一,并檢查下一個或多個元素是否為數字,回傳數字或那些數字
但是我的代碼只適用于 entry 元素之后的 1 個數字元素,正如我之前提到的,我想要在 entry 元素之后有多個數字,直到它到達字串型別的元素。
這是我的代碼:
const entry = [
'ENTRY', 'ZONE', 'ENTRI', 'ENTRE', 'ENTR', 'ZON', 'ZONI'
];
const text = ['HI', 'GOOD', 564, 'CLX', 'ENTRI', 'YYY', 'ENTRY', 657, 780, 34, 'XXX'];
const set = new Set(entry);
let result = [];
for (let i = 0; i < text.length; i ) {
let curr = text[i],
next = text[i 1];
if (set.has(curr) && typeof next == 'number') {
result.push(next);
}
}
console.log(result)
所以這是輸出:
//output : [ 657 ]
我想要的是 :
//output : [657 , 780 , 34]
uj5u.com熱心網友回復:
您可以在同一個回圈變數上添加嵌套回圈并添加陣列值,只要它們是數字即可。
const entry = [
'ENTRY', 'ZONE', 'ENTRI', 'ENTRE', 'ENTR', 'ZON', 'ZONI'
];
const text = ['HI', 'GOOD', 564, 'CLX', 'ENTRI', 'YYY', 'ENTRY', 657, 780, 34, 'XXX'];
const set = new Set(entry);
let result = [];
for (let i = 0; i < text.length; i ) {
if (set.has(text[i])) {
while (typeof text[i 1] == "number") {
result.push(text[ i]);
}
}
}
console.log(result)
uj5u.com熱心網友回復:
您的條件表示有效元素必須緊跟在 set 成員之后,該成員僅適用于第一個元素而不是每個元素。
一種不同的方法是打開一個發現成員的標志,并在到達另一個不是成員的字串時將其關閉。
const entry = ['ENTRY' , 'ZONE' , 'ENTRI' , 'ENTRE' , 'ENTR' ,'ZON' , 'ZONI'];
const text = ['hi' , 'good' , 564 , 'clx' , 'entri' , 'yyyy' , 'ENTRY' ,657 , 780 , 34 , 'xxxx'];
const set = new Set(entry);
let result = [];
let isAfterMatch = false
for (let i = 0; i < text.length; i ) {
const curr = text[i];
if (isAfterMatch && typeof curr === 'number') {
result.push(curr);
} else {
isAfterMatch = set.has(curr)
}
}
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321540.html
標籤:javascript 数组
下一篇:C 修改通過引數傳遞的陣列
