Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - 有没有办法在JavaScript中将多个对象属性设置为一个值?(Is there a way to set multiple object properties to one value in JavaScript?)

I know that you can do let a = b = c = d = 10;(我知道您可以let a = b = c = d = 10;)

but when I have values in object like so let key = {w : false, a : false, s : false, d : false};(但是当我在对象中具有这样的值时, let key = {w : false, a : false, s : false, d : false};) can I somehow set all values to false at once?(我可以以某种方式一次将所有值设置为false吗?) I couldnt find answer.(我找不到答案。) I tried something like(我尝试了类似的东西) let key = {w,a,s,d => false}; let key = {w : a : s : d : false}; let key = {w,a,s,d : false}; Is it possible to do something like this in js?(可以在js中做类似的事情吗?)   ask by Stanislav Tokár translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can manually set the values in a chain:(您可以手动设置链中的值:)

const obj = {}; obj.w = obj.a = obj.s = obj.d = false; console.log(obj) You can iterate the array of keys with Array.forEach() , and set the values:(您可以使用Array.forEach()迭代键数组并设置值:) const updateObj = (value, keys, obj) => keys.forEach(k => obj[k] = value) const obj = { w: true, a: true, s: true, d: true }; updateObj(false, Object.keys(obj), obj); console.log(obj) updateObj(true, ['w', 's'], obj); console.log(obj)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...