Array.push return pushed value?

前端 未结 6 1937
盖世英雄少女心
盖世英雄少女心 2021-01-04 02:30

Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?

I

6条回答
  •  再見小時候
    2021-01-04 03:09

    By the coming of ES6, it is recommended to extend array class in the proper way , then , override push method :

    class XArray extends Array {
       
       push() {
         super.push(...arguments);
         return (arguments.length === 1) ? arguments[0] : arguments;
       }
     
    }
    //---- Application
    let list  = [1, 3, 7,5];
    
    list = new XArray(...list);
    
    console.log(
      'Push one item : ',list.push(4)
    );
    
    console.log(
      'Push multi-items :', list.push(-9, 2)
    );
    
    console.log(
       'Check length :' , list.length
    )

提交回复
热议问题