Array,prototype.concat.apply與[].conat.apply.

來源:互聯網
上載者:User

標籤:str   ber   push   數列   對象   協助   位置   字元   AC   

 

 

 一直都知道JS數組Array內建對象有一個concat方法,但是也沒怎麼研究過,今天偶然就看了看

  concat是串連一個或多個數組

 返回的是串連後數組的一個副本

var oldArr=[];

var arr=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]];

var newArr=oldArr.conat(arr);

console.log(newArr);

 

 

 

console.log(oldArr);//[]  沒有改變

 

於是乎 我又想到把數組的每一項都當成數組與oldArr串連

這就需要apply方法了 將數組變成參數列表傳參

console.log(Array.prototype.concat.apply(Array,arr));

//結果很奇怪

沒有得到想到的結果

 

 

 箭頭地方是什麼鬼???

 想了想

 Array.prototype.concat.apply(Array,arr);

 不就是Array調用了Array.prototype上的concat然後傳入參數arr

把Array 換成Number String 等 不就是 借用Array.prototype上的concat方法罷了

然後把調用者添加到數組的0位置

我感覺就是 arr.unshift(Array);

其他情況的話就會 push 了

看下面的圖就明白了吧

console.log(Array.prototype.concat.apply(Number,arr));

 

console.log(Array.prototype.concat.apply(String,arr));

 

console.log(Array.prototype.concat.apply(RegExp,arr));

 

 好像是這麼回事

所以 把aplly裡面的參數改成[]不就好了

console.log(Array.prototype.concat.apply([],arr));

可以簡單點寫[].concat.apply([],arr);

 

  數組不僅可以串連數組  數組還可以連接字串  數字  對象  等

   console.log([].concat({a:2,b:3,c:3}));

 

 他會把對象放在數組裡,這裡就不能說串連了吧 我中有你嘛

console.log([].concat("123"}));

 

根據這些我總結出了  如果 concat傳入的參數不是數組 就不會遍曆 直接暴力添加到數組項

而參數是數組的話就會遍曆

 

需要注意的是  千萬不要傻傻的 用String.concat(); Number.concat()等

上面的是用apply方法改變this指向借用的

它本身沒有concat

String.prototype裡面有concat但是實現結果不一樣滴!

只是我個人的理解 希望對大家有協助

  

Array,prototype.concat.apply與[].conat.apply.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.