Javascript Array.prototype.map()函数与JS对象的行为
我正在尝试以下代码:Javascript Array.prototype.map()函数与JS对象的行为,javascript,arrays,Javascript,Arrays,我正在尝试以下代码: let obj ={}; let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => { obj.count= Math.random()*el.length; obj.ingredient= el; return obj; }); console.log(newIngredients); 这是我得到的输
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);
就像这样做:
let first={};
第一,a=1;
让第二个=第一个;
第二,a=2;
console.log(first.a);//这与Array.prototype.map()无关,而是与javascript中的对象行为有关
例如,如果您运行此
让obj={};
设prev=obj;
let NewComponents=[“你好”,“分心”,“没事”,“爱”]。地图(el=>{
obj={
计数:Math.random()*el.length,
成分:香精
};
如果(obj==上一个){
console.log(true);
}否则{
console.log(false)
}
prev=obj;
返回obj;
});
console.log(新成分)代码>
+−−−−−−−−−−−−−−−−−−−−−−−−−−−+
obj:Ref11654−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−>| (object) |
/ / / / +−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| | | | | count: 1.4648989727265578 |
| | | | | ingredient: "Love" |
| | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| | | |
+−−−−−−−−−−−−−+ | | | |
newIngredients−−−>| (array) | | | | |
+−−−−−−−−−−−−−+ | | | |
| 0: Ref11654 |−+ | | |
| 1: Ref11654 |−−−+ | |
| 2: Ref11654 |−−−−−+ |
| 3: Ref11654 |−−−−−−−+
+−−−−−−−−−−−−−+