gpt4 book ai didi

javascript - 替换行索引的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:15 24 4
gpt4 key购买 nike

一般来说:

我有一条短信

Sample1 Text1 Line 1
Sample2 Text2 Line 2
Sample3 Text3 Line 3

和一个数组 ['LEFT', 'RIGHT', 'CENTER'] 表示对齐..

假设,我删除了 Line 1 Sample2 这使得文本为:

Sample1 Text1 
Text2 Line 2
Sample3 Text3 Line 3

Alignment 数组应该保持不变:['LEFT', 'RIGHT', 'CENTER']但是,如果我删除第二行,数组应该更改为 ['LEFT','CENTER']

反之亦然...在第 1 行和第 2 行之间添加一行时,它应该将数组更改为 ['LEFT', 'LEFT', 'RIGHT', 'CENTER']通过从“扩展”线对齐...

是的...我知道...令人困惑...

https://jsfiddle.net/redlive/yuz08axc/

最佳答案

你要这个吗

let text = 'a\nb\nc\n'
const textAsArray = text.split('\n')
const alignments = ['left', 'right', 'center']

// initial
console.log('initial state:', text, alignments)

// remove second line
removeLine(1)
console.log('removed second line:', text, alignments)


// add second line
addLine(1, 'b')
console.log('added second line:', text, alignments)

function removeLine(num) {
textAsArray.splice(num,1)
alignments.splice(num,1)
text = textAsArray.join('\n')
}


function addLine(num, val) {
textAsArray.splice(num, 0, val)
alignments.splice(num, 0, alignments[num ? num - 1 : 'left' /* left is default */ ])
text = textAsArray.join('\n')
}

关于javascript - 替换行索引的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com