我有两个关于解构数组的新手问题:
第一个问题:当解构一个对象时,我可以定义一个新的值或者一个新的键,或者两者都定义。在数组上,我可以在不添加新键的情况下添加新值吗?
const obj = {a: undefined, b:2};
const {a = 3, b} = obj;
console.log(a); // 3我想知道是否有一个版本,但用数组代替。
第二个问题:有没有可能不为对象提供默认值?考虑到我认为使用destructure改变默认值是不可能的。
const obj = [1, {a: 1, b:2}, 3, 4];
const [, object, three, four] = obj;
console.log(object); //{a: 1, b:2}在本例中,object返回{a: 1, b:2},但我希望它改为更改该值。这有可能吗?
谢谢,致敬。
发布于 2020-06-12 07:56:03
您混淆了默认值与值的突变,以及将值赋值给变量与对象的突变。下面是解构的默认值功能的演示,并带有注释来解释该行为。
您将在这里看到,一般来说,解构不是为对象的突变而设计的,而是为了提取变量和值而设计的。希望也能感受到为什么突变混合在其中是不可取的,即使它是可能的。
const obj = [1, {a: 1, b:2, 99:'z'}, ,3, 4, {mutateme: 1}];
const [, {a=3,b=4,c=5}, object={a:7,b:7},three, four, object2] = obj;
// a prop has value=1, b has value=2, c is not defined use default value 5
console.log(a,b,c,object);
//object is empty use default value={a:7,b:7}
// obj is unchanged
console.log(obj)
// mutate object2={mutateme:1} by reference (like a pointer)
object2.mutateme=7
// {mutateme: 1=>7}
console.log(obj)
// example of how you could (sort of) mutate inside a destructuring statement
// computed property, obj[1]=obj[3]=99 returns 99,
// so extract property 99 to variable z and mutate object obj at index [1] and [3] to =99
// y will 99 now.
const [y1, {[obj[1]=obj[3]=99]:z},, y2 ] = obj
console.log(y1, z, y2)
// if something similar were built into destructuring syntax,
// can you imagine how confusing it could get, and cause of all kinds of unexpected behavior?
https://stackoverflow.com/questions/62335293
复制相似问题