更新時間:2020-11-02 17:57:04 來源:動力節(jié)點 瀏覽2521次
數(shù)組是在程序設(shè)計中,為了處理方便, 把具有相同類型的若干元素按有序的形式組織起來的一種形式。我們可以把數(shù)組看成是用于儲存多個相同類型數(shù)據(jù)的集合,我們在需要用到數(shù)組中的一部分?jǐn)?shù)據(jù)時,就需要用到數(shù)組解構(gòu),獲得相應(yīng)的數(shù)據(jù)。本文我們就一起來學(xué)習(xí)Java數(shù)組解構(gòu)的相關(guān)知識。
1.簡單解構(gòu)
const numbers = ['a', 'b', 'c'];
// 獲取前兩項
const [n1, n2] = numbers;
console.log(n1,n2)// 'a' , 'b'
// 獲取第一項和第三項
const [n1, , n3] = numbers;
console.log(n1,n3)// 'a' , 'c'
// 獲取第一項和第四項
const [n1, , n3, n4] = numbers;
console.log(n1,n3,n4)// 'a' , 'c', undefined
// 給默認(rèn)值
const [n1, , n3, n4 = 'd'] = numbers;
console.log(n1,n3,n4)// 'a' , 'c', 'd'
2.嵌套數(shù)組解構(gòu)
// 得到numbers中下標(biāo)為4的數(shù)組中的下標(biāo)為2的數(shù)據(jù),放到變量n中
const [, , , , [, , n]] = numbers;
console.log(n); // 3
嵌套對象解構(gòu)
賦給同名變量
const numbers = ['a', 'b', 'c', 'd', {
a: 1,
b: 2
}];
// 得到numbers中下標(biāo)為4的數(shù)組的屬性a,賦值給變量a
const [, , , , { a }] = numbers
console.log(a); // 1
賦給不同名變量
const numbers = ['a', 'b', 'c', 'd', {
a: 1,
b: 2
}];
// 得到numbers中下標(biāo)為4的數(shù)組的屬性a,賦值給變量A
const [, , , , { a: A }] = numbers
console.log(A); // 1
3.解構(gòu)剩余項
const user = {
name: 'lisa',
age: 20,
sex: '女',
address: {
province: '江蘇',
city: '無錫'
}
}
// 解構(gòu)出name,然后剩余的所有屬性,放到一個新的對象中,變量名為obj
// 最后得出
// name:lisa
// obj:{ age: 20,sex: '女', address: {···}}
const { name, ...obj } = user;
console.log(name, obj);
解構(gòu)數(shù)組的剩余項
const numbers = [1, 2, 3, 4];
// 得到數(shù)組前兩項,前兩項放到變量a和b中,然后剩余的所有數(shù)據(jù)放到數(shù)組nums中
const [a, b, ...nums] = numbers;
console.log(a, b, nums); // 1, 2, [3, 4]
我們再來看下面的例子:
const article = {
title: "文章標(biāo)題",
content: "文章內(nèi)容",
comments: [{
content: "評論1",
user: {
id: 1,
name: "用戶名1"
}
}, {
content: "評論2",
user: {
id: 2,
name: "用戶名2"
}
}]
}
//解構(gòu)出第二條評論的用戶名和評論內(nèi)容
// name:"用戶名2" content:"評論2"
const { comments: [, { content, user: { name } }] } = article;
以上就是Java數(shù)組解構(gòu)的相關(guān)知識,當(dāng)然這些只是大概的講解,想要更加詳細(xì)的講解過程可以觀看本站的Java基礎(chǔ)教程,幫你全面學(xué)習(xí)和鞏固Java基礎(chǔ)知識。
初級 202925
初級 203221
初級 202629
初級 203743