这是我的代码 - 我想将字符串“areas”的一部分存储到数组中。 不幸的是,我的数组元素未定义。我对 javascript 和整个编码都很陌生。
任何帮助都会很棒:-)
let areas = '10101101110001101010011101001110000101011000101010100010011001101100110110011010000101001110101';
// checking guards
leftGuard = areas.substr(0,3);
if (leftGuard !== '101')
{
return result.message1;
}
centerGuard = areas.substr(45,5);
if (centerGuard !== '01010')
{
return result.message2;
}
rightGuard = areas.substr(92,3);
if (rightGuard !== '101')
{
return result.message3;
}
// segregate the areas string into left and right digit and store in an array
let newAreaLeft = areas.slice(3,45);
let newAreaRight = areas.slice(51,92);
// left nos.
let i = 0, j = 0;
while (j < 42)
{
realLeft[i] += newAreaLeft.substr(j,7);
j += 7;
i++
}
输出:
未定义0110111,未定义0001101,未定义0100111,未定义0100111,未定义0000101,未定义0110001
最佳答案
数组中未初始化的元素以 undefined
形式返回,在字符串表达式中转换为“undefined”。
尝试使用直接赋值而不是 +=
设置 realLeft
来覆盖未定义的条目(如果可以接受):
realLeft[i] = newAreaLeft.substr(j,7);
或者在附加之前将未初始化的值设置为空字符串:
realLeft[i] = realLeft[i] || ""; // change falsey values to empty string
realLeft[i] += newAreaLeft.substr(j,7);
关于javascript - 为什么对这个字符串进行切片并使其成为数组会向数组的元素添加 undefined ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51851437/