我正在尝试以下代码:
let obj ={};
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
obj.count= Math.random()*el.length;
obj.ingredient= el;
return obj;
});
console.log(newIngredients);
这是我得到的输出:
(4) [{…}, {…}, {…}, {…}]
0: {count: 1.4648989727265578, ingredient: "Love"}
1: {count: 1.4648989727265578, ingredient: "Love"}
2: {count: 1.4648989727265578, ingredient: "Love"}
3: {count: 1.4648989727265578, ingredient: "Love"}
length: 4
__proto__: Array(0)
这不是我想要的。但是当我输入以下内容时,
let obj;
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
obj = {
count: Math.random()*el.length,
ingredient: el
} ;
return obj;
});
console.log(newIngredients);
它返回以下输出,这是我真正想要的:
(4) [{…}, {…}, {…}, {…}]
0: {count: 4.2813861024052615, ingredient: "Hello"}
1: {count: 5.850654082147917, ingredient: "Distraction"}
2: {count: 6.646446034466489, ingredient: "Nothing"}
3: {count: 1.7062874250924214, ingredient: "Love"}
length: 4
__proto__: Array(0)
谁能解释为什么这两个代码片段之间的行为存在差异?
最佳答案
在您的第一个示例中,您只创建了一个对象,然后将它放入数组中四次:
let obj ={}; // <===== Creates the one object
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
obj.count= Math.random()*el.length;
obj.ingredient= el;
return obj; // <===== Puts it in the array four times
});
console.log(newIngredients);
因为只有一个对象,所以每次执行 obj.ingredient = el;
时,您都更新了属性,替换了它之前的值。
结果在内存中看起来是这样的:
+−−−−−−−−−−−−−−−−−−−−−−−−−−−+ obj:Ref11654−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−>| (object) | / / / / +−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | | | | | count: 1.4648989727265578 | | | | | | ingredient: "Love" | | | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | | | | +−−−−−−−−−−−−−+ | | | | newIngredients−−−>| (array) | | | | | +−−−−−−−−−−−−−+ | | | | | 0: Ref11654 |−+ | | | | 1: Ref11654 |−−−+ | | | 2: Ref11654 |−−−−−+ | | 3: Ref11654 |−−−−−−−+ +−−−−−−−−−−−−−+
It's exactly like doing this:
let first = {};
first.a = 1;
let second = first;
second.a = 2;
console.log(first.a); // 2, not 1
您的第二个示例为每次调用 map
回调创建了一个对象,这是正确的,尽管不需要 obj
变量并且拥有它有点误导.所以:
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
return {
count: Math.random()*el.length,
ingredient: el
};
});
console.log(newIngredients);
或者用一个简洁的箭头函数:
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => ({
count: Math.random()*el.length,
ingredient: el
}));
console.log(newIngredients);
关于javascript - Array.prototype.map() 函数与 JS 对象的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62482732/