Two arrays: textArr
and valueArr
, combine these two arrays to form a string such as: 1^Q1
. Separate them with \n
. (Preparing to pass it into textarea)
Every time, an extra blank line is added to the head of the string. The code is very short, but I can't find it, which is frustrating. Please help and take a look. Thanks!
choicesToString () {
let textArr = ['Q1', 'Q2', 'Q3'];
let valueArr = [1, 2, 3];
let choiceArr = []
for (let i = 0; i < textArr.length; i++) {
if (isNull(valueArr[i])) { valueArr[i] = '' }
if (isNull(choiceArr[i])) { choiceArr[i] = '' }
if ((valueArr[i] === '') && (choiceArr[i] === '')) { continue }
choiceArr.push(valueArr[i] + '^' + textArr[i])
console.log(`${i}: ${choiceArr}`)
}
// TODO: BUG! Add an empty cell at the first position. FUCK!!!
// 难道要我被迫加上这段可耻的代码...
// choiceArr.splice(0, 1)
console.log(choiceArr)
return choiceArr.toString().split(',').join('\n')
}
isNull (arg) {
return !arg && arg !== 0 && typeof arg !== 'boolean' ? true : false
}
You wrote all the judgments of
valueArr
intochoiceArr
for
loop Wheni
is equal to0
, look at this sentenceAt this time,
choiceArr
is[]
,choiceArr[i]
ischoiceArr[0]
, which isundefined
,isNull
will returntrue
, sochoiceArr[i] = ' '
, at this time, the length of the array has become1
, and then after executing the push below, the value ofchoiceArr
at this time is["", "1^Q1"]
, so the for loop After one pass, the length ofchoiceArr
is not1
but2
.When
The judgment ofi
is equal to1
, because the value ofchoiceArr[1]
is"1^Q1"
, sois
false
, and then execute the push statement below. At this time, the value ofchoiceArr
is["", "1^Q1", "2^Q2"]
;when
i
is equal to2 When
is the same as wheni=1
, after the loop ends,choiceArr
is["", "1^Q1", "2^Q2", "3^Q3"]
.To sum up, the null value
""
is generated wheni=0
.As mentioned above, your sentence
if (isNull(choiceArr[i])) { choiceArr[i] = '' }
is very strange. If you have to write it like this, just add a judgment.