簡體   English   中英

用數組元素填充空白

[英]fill blank with elements of array

我想用參考數組填充“_”:

 const reference = ['this is', 'a beautiful', 'car']; const blank = ['I know', '_']; console.log(fillBlank(reference)) function fillBlank(reference) { const ref = reference.join(' '); if(blank.length) { return // I know this is a beautiful car } else { return ref; } }

請注意,我們可能在不同的地方有空白,但我們在每個空白數組中只有一個:

const blank = ['I know', '_'];
const blank = ['_', 'I know'];
const blank = ['I know', '_', 'right?'];

我怎樣才能做到這一點?

您可以映射和加入

 const reference = ['this is', 'a beautiful', 'car']; const ref = reference.join(' '); const fillBlank = (blank,ref) => blank.map(item => item === "_" ? ref : item).join(", ") console.log(fillBlank(['I know', '_'],ref)) console.log(fillBlank(['_', 'I know'],ref)) console.log(fillBlank(['I know', '_', 'right?'],ref))

如果需要,我們可以更進一步,將 ref 的第一個字母大寫

 const reference = ['this is', 'a beautiful', 'car']; const ref = reference.join(' '); const fillBlank = (blank,ref) => blank.map((item,i) => item === "_" ? i>0? ref : ref.slice(0,1).toUpperCase() + ref.slice(1) : item).join(", ") console.log(fillBlank(['I know', '_'],ref)) console.log(fillBlank(['_', 'I know'],ref)) console.log(fillBlank(['I know', '_', 'right?'],ref))

試試這個而不是“返回//我知道這是一輛漂亮的車”:

return blank.map(item => item === '_' ? ref : item).join(' ')
function fillBlank(arrToReplace, reference) { const concatedRef = reference.join(' '); arrToReplace.splice(arrToReplace.findIndex(el => el === '_'), 1, concatedRef); return arrToReplace.join(' '); }

這應該有效。 本質上,您將找到空白的位置並將其替換為 Reference 數組的內容。

 const reference = ['this is', 'a beautiful', 'car']; const blank = ['I know', '_']; console.log(fillBlank(reference)) function fillBlank(reference) { if(blank.length) { const res = [...blank]; //Find the blank first const idx = res.findIndex(item => item === '_'); //Replace the '_' with the array items res.splice(idx, 1, ...reference) const final = res.join (' '); return final; // I know this is a beautiful car } else { return ref; } }

如果你想用另一個數組填充一個數組中的一個索引,你可以在javascript中使用 splice 函數。

const reference = ['this is', 'a beautiful', 'car'];
const blank = ['I know', '_', 'Right?'];

console.log(fillBlank(reference));
                
function fillBlank(reference) {
    const isBlank = (element) => element == '_';
    const blankIndex = blank.findIndex(isBlank);
                    
    if (blankIndex > 0) {
        blank.splice(blankIndex, 1, ...reference);
        return blank
    }
    return ref;
}

splice 函數的工作原理是這樣的:你給它一個起始索引、要刪除的元素數量以及要放在那里的元素。

'...' 是一個擴展運算符,它將擴展引用的元素,因此它不是數組,而是單獨為您提供每個項目

 function fillBlank(blank, reference) { return blank.join(' ').replace('_', reference.join(' ')); } const filled_blank = fillBlank( ['I know', '_'], ['this is', 'a beautiful', 'car'] ); console.log(filled_blank);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM