【问题标题】:JavaScript Array Elements undefined [duplicate]JavaScript数组元素未定义[重复]
【发布时间】:2022-01-05 13:48:00
【问题描述】:

我正在处理一些我存储在 Nodejs 数组中的 HRV 数据。但是,每当我想访问存储在所述数组中的值时,它都会显示为“未定义”。我想读取的数组是由这段代码生成的:

let rr_data = [456,782,365,234,783,456,987,456,782,365,234,783,456,987,456,782,365,234,783,456,987]
let t = []
rr_data.reduce((current, next, i) => {
        return t[i] = current + next
    })

当我现在控制台日志“t”(console.table(t))时,它看起来像这样:

但是,每当我尝试单独访问一个元素时,例如console.log(t.at(0))console.log(t[0]),它都会显示为“未定义”。为什么会发生这种情况,我该如何预防?

感谢您的帮助!

【问题讨论】:

  • 你能解释一下return t[i] = current + next 应该做什么吗?
  • 它添加单元格值..
  • 只有索引 0 不存在,因为您没有为 reduce 提供初始值。因此,第一个元素(索引 0)作为初始值,reduce 从索引 1 开始。您可以在回调中添加类似 console.log({ current, next, i }); 的内容,以帮助您了解发生了什么。
  • 谢谢!我通过 t[t.length] 和 t[0] 访问它,并认为整个数组都丢失了。真是愚蠢的错误。谢谢你帮助我!
  • 每当您提出这样的问题时,请务必在问题中包含您想要的结果。因为您没有,所以您有两个答案,其中一个为您提供456 的第一个元素t(只是rr_data[0] 的值不变),其中一个为您提供1238 的第一个值(rr_data[0]rr_data[1]相加的结果)。

标签: javascript node.js arrays


【解决方案1】:

当您调用reduce 时没有任何累加器的种子值(即没有第二个参数),它会首先使用数组中的前两个值调用您的回调,并将索引设置为1。所以i 在你的代码中,在第一个回调中,是1,而不是0,你永远不会分配给t[0],所以它会保持undefined。 (如果您的数组中根本没有元素,它也会引发错误。)这是reduce 对于大多数使用预定义的、可重用的 reducer 函数的函数式编程之外的用例过于复杂的原因之一。

如果您只想用源数组中的元素 nn+1 组合的结果填充 t,那么简单的循环可能是您更好的选择:

for (let index = 0; index < rr_data.length; index += 2) {
    const next = rr_data[index + 1] ?? 0; // In case that's past the end
    t.push(rr_data[index] + next);
}

现场示例:

let rr_data = [456,782,365,234,783,456/*...*/];
let t = [];
for (let index = 0; index < rr_data.length; index += 2) {
    const next = rr_data[index + 1] ?? 0; // In case that's past the end
    t.push(rr_data[index] + next);
}
console.log(t);

【讨论】:

  • Reduce 是这个用例的完美功能..
  • @Tasos - 我不同意,但你也有权发表你的意见。同样,FP 人员将它与预定义、经过测试、可重用的减速器一起使用没有问题,但在那个专业用例之外,我(和someothers)随着时间的推移了解到,这只是一个过于复杂的循环,会引发维护问题.
【解决方案2】:

这里没有错。

Array.reduce() 中,您可以传递一个初始值。您的问题是您的初始值未定义,这就是 t[0] 不是数字的原因。

如果您将代码更改为此它应该可以工作:

let rr_data = [456,782,365,234,783,456,987,456,782,365,234,783,456,987,456,782,365,234,783,456,987]
let t = []
rr_data.reduce((current, next, i) => {
        return t[i] = current + next
    }, 0)
console.log(t)
console.log(t[0])

【讨论】:

  • 谢谢!我这边真是愚蠢的错误......
  • 别担心,伙计
  • 这里不需要return 指令。
【解决方案3】:

let arr = [456, 782, 365, 234, 783, 456, 987, 456, 782, 365, 234, 783, 456, 987, 456, 782, 365, 234, 783, 456, 987];
let t = [];
arr.forEach ((item, i) => {
if (i != arr.length-1) {
    t[i] = arr[i+1] + arr[i];
}
});

【讨论】:

    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2018-08-27
    相关资源
    最近更新 更多