JavaScript 如何從參考型別(Array 、 Object)建立一個新的對象

來源:互聯網
上載者:User

標籤:let   book   要求   slice   cti   更新   特性   function   dex   

數組的增刪改查

1、新增一項
可以使用concat方法,它不會對原有數組進行改動,而是建立一個新數組

let a = [0, 1, 2]let b = a.concat([3])console.log(a, b)

2、刪除一項
對於刪除某一項的操作,splice也不能滿足要求,因為該方法會改變原有數組,相應地我們應該使用slice,並結合es next 新特性。

let array = [1,2,3]const removeIndex =  (array, index) => {    return [        ...array.slice(0, index),        ...array.slice(index + 1),    ]    }let newArray = removeIndex(array, 1);

3、更新一項

let array = [1, 2, 3];const updateIndex = (array, index, cb) => {    return [        ...array.slice(0, index),        cb && cb(array[index]),        ...array.slice(index + 1),    ]    }updateIndex(array, 1, function (data) {    return data + 1;});

4、新增也可以使用這種思路,比concat要靈活

let array = [1, 2, 4];const insertIndex = (array, index, value) => {    return [        ...array.slice(0, index),        value,        ...array.slice(array.length - 1),    ]    }insertIndex(array, 2, 3);
 

 

 

對象的增刪改查

1、更新一項

使用ES next新特性的 Object.assign 方法。

第一個參數必須是Null 物件,因為第一個參數會被改變(接受合并所有參數的值)
我們要更新的值必須放在最後面,因為參數越往後,許可權越高。才能覆蓋前者重複的內容

let sourceItem = {    id: 0,    book: ‘Learn Redux‘,    avaliable: false}Object.assign({}, sourceItem, {    avaliable: true})

2、對象操作:新增一項

其實和上面一樣,寫入新的索引值對就算新增嘛

let sourceItem = {    id: 0,    book: ‘Learn Redux‘,    avaliable: false}Object.assign({}, sourceItem, {    fuck: 123})

3、對象操作:刪除一項

let sourceItem = {    id: 0,    book: ‘Learn Redux‘,    avaliable: false,    fuck: 123}let newItem = Object.key(sourceItem).reduce((obj, key) => {    if (key !== ‘fuck‘) {        return { ...obj, [key], sourceItem[key] }    }    return obj}, {})

 

JavaScript 如何從參考型別(Array 、 Object)建立一個新的對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.