我已经为这个问题寻找了好几个星期的答案,但我不明白我到底做错了什么,或者说我期待的是什么... ...
let simpleArray = [{"weight": "2kg"},{"weight": "5kg"}];
// I want to turn the weight value string to number without modifying the original array
function kilosNumber(arrayToSort){
//Copy to a new array so we don't screw up the original
const sortedArray = [...arrayToSort];
//If you dont use spread operator or .slice() trick the next step returns true
// check that the source is diferent
console.log(sortedArray === arrayToSort);//false, so its not the same
//Let's map the array and change the item weight
sortedArray.map(function(object){
return object.weight = parseFloat(object.weight);
});
return sortedArray;
};
// It returns what I want
console.log(kilosNumber(simpleArray));
// But it modifyes the original
console.log(simpleArray);
在使用之前,你不需要展开 Array.map()
因为 Array.map()
生成一个新的数组。在映射的时候,使用对象展期来生成具有更新值的新对象。
const simpleArray = [{"weight": "2kg"},{"weight": "5kg"}];
function kilosNumber(arr) {
return arr.map(o => ({
...o,
weight: parseFloat(o.weight)
}));
};
// It returns what I want
console.log(kilosNumber(simpleArray));
// But it modifyes the original
console.log(simpleArray);
Spread语法会对你的数组进行浅层复制,因此对象中的嵌套对象键不会被克隆,你也需要克隆它们,而不是突变它们。另外,当使用 map
你需要使用返回值
let simpleArray = [{"weight": "2kg"},{"weight": "5kg"}];
function kilosNumber(arrayToSort){
//Let's map the array and change the item weight
let sortedArray = simpleArray.map(function(object){
return { ...object, weight: parseFloat(object.weight)};
});
return sortedArray;
};
console.log(kilosNumber(simpleArray));
console.log(simpleArray);