gpt4 book ai didi

javascript - 使用 .map 影响整个对象(使其未定义)而不是更新属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:14 25 4
gpt4 key购买 nike

当我这样做时:

csvParse(txtString, {columns: true})

我得到一个对象数组,我想在其中更新每个对象的特定属性。

但是所有发生的事情是对象变得未定义。

这完全符合我的预期:

let x = [{
y: 123,
z: 'abc'
}, {
y: 456,
z: 'efg'
}, {
y: 789,
z: 'hij'
}];

console.log(x);

x.map(x => {
x.z.toUpperCase();
});
console.log(x); // no changes saved

x.map(x => {
x.z = x.z.toUpperCase();
});
console.log(x); //now z is uppercase

但是当我在我的代码中做同样的事情时:

resolve(
csvParse(txtString, {
columns: true
})
.map(x => {
x.categories = x.categories
.replace(regexes.doubleQuotesOrSquareBrackets, '')
.split(',');
})
);

结果数组中的每个元素都未定义。

最佳答案

ES6 函数的工作方式是,当有单个语句时它返回计算值,如果有多个语句则需要显式使用 return

在您的情况下,您的单个语句是一个赋值操作。

所以它在技术上返回 undefined

.map(x => {
x.categories = ...
});

只不过是

.map(x => {
x.categories = ...
return undefined;
});

要修复它,您可以这样做

.map(x => {
x.categories = ...;
return x.categories;
});

.map(x => {
...;
return x;
});

关于javascript - 使用 .map 影响整个对象(使其未定义)而不是更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475563/

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