无法使用 concat 将元素推入空数组
Unable to push the elements into empty array using concat
我尝试使用 concat
但无法获得像 [1,2,66]
这样的数组。通过使用 push
我得到了。但是使用 concat 是否可能或者我没有得到结果的原因是什么。
const arr = [1, 2, 66];
const data = arr.reduce((obj, k) => {
obj.concat(k);
return obj
},[]);
console.log(data);
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
因此,obj.concat(k)
不执行任何操作,您在下一行 returning 未更改 obj
。
要解决这个问题,您可以将 concat 分配给一个新变量,然后 return 那...
const newObj = obj.concat(k);
return newObj;
... 或者只是 return concat 的结果:
return obj.concat(k);
const arr = [1, 2, 66];
const data = arr.reduce((obj, k) => {
return obj.concat(k);
}, []);
console.log(data);
我尝试使用 concat
但无法获得像 [1,2,66]
这样的数组。通过使用 push
我得到了。但是使用 concat 是否可能或者我没有得到结果的原因是什么。
const arr = [1, 2, 66];
const data = arr.reduce((obj, k) => {
obj.concat(k);
return obj
},[]);
console.log(data);
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
因此,obj.concat(k)
不执行任何操作,您在下一行 returning 未更改 obj
。
要解决这个问题,您可以将 concat 分配给一个新变量,然后 return 那...
const newObj = obj.concat(k);
return newObj;
... 或者只是 return concat 的结果:
return obj.concat(k);
const arr = [1, 2, 66];
const data = arr.reduce((obj, k) => {
return obj.concat(k);
}, []);
console.log(data);