js擴展運算符,神奇的3個點點,數組去重、合併數組等等

最近lz一週排了9個面試,面試常常被問到一些數組的問題,好比說es6裏面一些數組去重、合併數組,以前壓根就沒了解過,後來才知道考的都是es6的知識,今天好好挖掘一下,發現一個神奇的點點三姐妹es6

咱們來看看常用的方法面試

一、數組去重

以前的想法可能要遍歷數組去重,可是如今又es6的騷操做
var a = [1,1,2,3]
    Array.from(new Set()) // 利用es6特性去重方法
    [...new Set(arr)]  // 利用js擴展運算符的騷操做

二、將一個數組放入另外一個數組(打散數組)

var a = [1,2]
    var b = [a,3,4]
    console.log(b) // [[1,2],3,4]
    
    // 若是使用擴展運算符
    var b = [...a, 3,4]
    console.log(b) // [1,2,3,4]

三、複製數組(不會改變原數組)

var a = ['1','2','3']
    var b = [...a]
    console.log(b) // ['1','2','3']  
    a數組中的元素擴展爲單獨元素被分配到b中,能夠隨意改變b數組,且不會對a產生影響。

四、 拼接數組(替換concat)

var a = [1,2,3]
    var a = [4,5,6]
    a  = [...a, ...b]
    console.log(a) // [1,2,3,4,5,6]

五、 Math

var a = [1,2,3,4,5]
    var max = Math.max(...a)
    console.log(max) // 5

六、字符串轉換爲數組

var a = 'helloworld'
    var b = [...a]
    console.log(b) // ['h','e','l','l','o','w','o','r','l','d']
相關文章
相關標籤/搜索