gpt4 book ai didi

Javascript concat 不是函数

转载 作者:行者123 更新时间:2023-11-30 11:23:14 28 4
gpt4 key购买 nike

嗨,这段代码不起作用,我收到错误 concat is not a function:我该如何解决?

var o=[{r:[3,8]},{r:[2,3,4]}];
undefined
var R=o.reduce(function(x,y,z){ return x.concat(y.r);})
VM200964:1 Uncaught TypeError: x.concat is not a function

最佳答案

您必须在 reduce 的第二个参数上将 x 初始化为数组 []

如果您不指定初始值(第二个参数),它将使用数组的第一个元素作为 x。这是一个对象,对象没有 concat 函数。

ES6 代码片段

var o=[{r:[3,8]},{r:[2,3,4]}];

var R=o.reduce((x,y) => x.concat(y.r) , []);

console.log( R );

也可以使用:

var R=o.reduce(function(x,y,z){ return x.concat(y.r);},[]);

文档:.reduce

关于Javascript concat 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011751/

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