我正在测试数组内的扩展运算符以映射另一个数组值。不幸的是,我想出了奇怪的行为或者我做错了。当我使用数组内的映射返回 2 个对象时,它只返回最后一个对象。代码如下:
const cats = ["Tom", "Ginger", "Angela"];
const array = [
// {
// name: "Ben",
// sex: "male"
// },
...cats.map((element, index, array) => {
return (
{
name: element,
sex: element !== "Angela" ? "male" : "female"
},
{
age: element !== "Angela" ? "20" : "18",
color:
element === "Tom"
? "black"
: element === "Ginger"
? "orange"
: "white"
}
);
})
];
console.log(array);
在控制台中:
[{"age":"20","color":"black"},
{"age":"20","color":"orange"},
{"age":"18","color":"white"}]
我的期望:
[{"name": "Tom", "sex": "male"},
{"age":"20","color":"black"},
{"name": "Ginger", "sex": "male"},
{"age":"20","color":"orange"},
{"name": "Angela", "sex": "female"},
{"age":"18","color":"white"}]
Codesandbox在这里。是否可以按照我的预期实现?或者还有其他选择吗?
您将返回两个带有逗号的对象。逗号运算符将仅返回最后一项。您需要返回一个数组并使用 flatMap
const cats = ["Tom", "Ginger", "Angela"];
const result = cats.flatMap(x => ([{
foo: x
}, {
bar: x
}]));
console.log(result);
问题本质上是你做了
return({},{})
而不是 return [{},{}]
。
(a,b)
称为逗号表达式,它计算第一个表达式 a
然后忽略结果,然后只返回第二个表达式 b
的计算结果。
const cats = ["Tom", "Ginger", "Angela"];
const array = cats.map((element) => [{
name: element,
sex: element !== "Angela" ? "male" : "female"
},
{
age: element !== "Angela" ? "20" : "18",
color:
element === "Tom"
? "black"
: element === "Ginger"
? "orange"
: "white"
}]
);
console.log(array);