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
}
曾经蜡笔没有小新2017-07-05 10:41:37
for
loop When i
is equal to 0
, look at this sentence
if (isNull(choiceArr[i])) { choiceArr[i] = '' }
At this time, choiceArr
is []
, choiceArr[i]
is choiceArr[0]
, which is undefined
, isNull
will return true
, so choiceArr[i] = ' '
, at this time, the length of the array has become 1
, and then after executing the push below, the value of choiceArr
at this time is ["", "1^Q1"]
, so the for loop After one pass, the length of choiceArr
is not 1
but 2
.
When i
is equal to 1
, because the value of choiceArr[1]
is "1^Q1"
, so
if (isNull(choiceArr[i])) { choiceArr[i] = '' }
The judgment of is false
, and then execute the push statement below. At this time, the value of choiceArr
is ["", "1^Q1", "2^Q2"]
;
when i
is equal to 2 When
is the same as when i=1
, after the loop ends, choiceArr
is ["", "1^Q1", "2^Q2", "3^Q3"]
.
To sum up, the null value ""
is generated when i=0
.
天蓬老师2017-07-05 10:41:37
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.
if (choiceArr.length > 0 && isNull(choiceArr[i])) { choiceArr[i] = ''; }