简体   繁体   English

Object.keys vs Object.value -.keys 发生变异而.value 没有。 为什么是这样?

[英]Object.keys vs Object.value - .keys mutates and .value does not. Why is this?

I am trying to change the values inside an object in Javascript, Object.values while running a forEach loop would seem to make the most sense to me but Object.keys (obj[key]) actually updated the value on the object. Here is my code to explain better.我正在尝试更改 Javascript 中的 object 中的值,Object.values 在运行 forEach 循环时对我来说似乎最有意义,但 Object.keys (obj[key]) 实际上更新了 object 上的值。这是我的代码解释得更好。

This way below works as expected下面的这种方式按预期工作

const usersKey = { user1: 18273, user2: 92833, user3: 90315 }

Object.keys(usersKey).forEach((key) => {
    usersKey[key] = usersKey[key]*2
    
})

console.log(usersKey)

This way below does not update the object下面这种方式不更新object


const usersValue = { user1: 18273, user2: 92833, user3: 90315 }

Object.values(usersValue).forEach((value) => {
    value = value*2
    
})

console.log(usersValue) 

Why is this?为什么是这样? Shouldn't both ways produce identical results?两种方式不应该产生相同的结果吗?

This behavior has nothing to do with Object.keys() and Object.values() as such.此行为与Object.keys()Object.values()本身无关。 They both return arrays with copies of keys/ values and do not mutate the object itself.它们都返回带有键/值副本的 arrays,并且不会改变 object 本身。

You're just accessing different values in your programs.您只是在程序中访问不同的值。 In the first program you are actually mutating the object itself, in the second program you only change the value which is a copy of the actual value.在第一个程序中,您实际上是在改变 object 本身,在第二个程序中,您只更改作为实际值副本的值。 As it is a primitive value the change of value is not reflected in the original value.由于它是原始值,因此值的变化不会反映在原始值中。

If you had eg an object as a value, then Object.values() would return a copy of the reference to that Object and therefore (as the reference points to the same data in memory) any change would also be reflected in the original array.例如,如果您将 object 作为值,则Object.values()将返回对该 Object 的引用的副本,因此(因为引用指向内存中的相同数据)任何更改也将反映在原始数组中.

 // now the values are not simple primitive types but an object const usersValue = { user1: { id: 18273 }, user2: { id: 92833 }, user3: { id: 90315 } } Object.values(usersValue).forEach((value) => { value.id = value.id*2 }) // changes are now reflected in the object console.log(usersValue)

See this thread for more information on pass-by-reference and pass-by-value.有关按引用传递和按值传递的更多信息,请参阅此线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM