使用解构为数组的值设置新值

set new value for array's value using destructure

我有两个关于解构数组的菜鸟问题:

第一个问题:当解构一个对象时,我可以定义一个新值或一个新键或两者。在阵列上,我可以在不添加新键的情况下添加新值吗?

const obj = {a: undefined, b:2};
const {a = 3, b} = obj;
console.log(a); // 3

我想知道是否有这个版本但是用数组代替。

第二个问题:是否可以不为对象提供默认值?考虑到我认为无法使用解构更改默认值。

const obj = [1, {a: 1, b:2}, 3, 4];
const [, object, three, four] = obj;
console.log(object); //{a: 1, b:2}

在此示例中,object returns {a: 1, b:2} 但我希望它改为更改值。那可能吗?

谢谢,问候。

您混淆了默认值和值的变化,以及将值赋给变量和对象的变化。下面是解构的默认值特性的演示,带有解释行为的注释。

你会看到这里一般来说,解构不是为了对象的变异而设计的,而是为了变量和值的提取。并且希望也能理解为什么将突变混入其中是不受欢迎的,即使它是可能的。

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?