JAvascript/フロントエンド配列に関する面接問題

26649 ワード

前言:最近面接では複数の配列に関する面接問題が聞かれ、普段は他の人も配列に関する問題を受験するのが好きです.ここでいくつかの例を挙げて記録します.
配列関連APIはあまり使われていない(ES 5/6/7新規部分、使用時は互換性に注意)ので分かりやすいが、組み合わせて使うと柔軟で出題が多く、面接者への説明も分かりやすい.使いこなせば、普段からコードを書く効率も向上し、比較的経験豊富なフロントエンド開発ではデータとの付き合いが避けられない.まとめると面接問題にぴったりです...
始める前に超実用的なツールライブラリlodashを推奨し、多くの実用的なツール関数を提供しています.
次のコードはES 6構文を使用しており、新しいChromeブラウザはbabelコンパイルを必要とせずに直接実行できます.
//  、       'abc123' => '321cba'

//        api        for  。。。        ,         。。
//     
'abc123'.split('').reverse().join('')
//  、       [1, [2, [3], 4], 5] => [1, 2, 3, 4, 5]
//        :
const arr = [1,[2,[3],4],5]
function flatten(arr) {
    for (let i in arr) {
        if (Array.isArray(arr[i])) {
            arr.splice(i, 1, ...flatten(arr[i]))
        }
    }
    return arr
}
flatten(arr)

//      arr.toString()   arr.join() => '1,2,3,4,5'
//          
const arr = [1,[2,[3],4],5]
arr.join()
	.split(',')
	.map(it => Number(it))

//      ,      。。。
const arr = [1, [2, [3], 4], 5]
JSON.parse(`[${arr}]`)

//                       ,    、                 ,                  ,         ,    。
//          ,      。        [underscore flatten](http://www.css88.com/doc/underscore/docs/underscore.html)    。
//  、       
// [1,2,3] => [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
//                 ,      ,                  。
//                    ,             ,            ,              ,               。。
function allRange (arr, path, res) {
    if (!arr.length) {
        res.push(path)
        return
    }
    arr.forEach((v, idx) => {
        const t = arr.slice()
        const p = path.slice()
        t.splice(idx, 1)
        p.push(v)
        allRange(t, p, res)
    })
}
var a = [1, 2, 3, 4]
const b = []
allRange(a, [], b)
console.log(b)
//----------------------20190204  -------------------
//           ,    reduce   ,        
console.log(
  [1,2,3,4].reduce((sum, p) => {
    if (sum.length === 0) return [[p]]
    const rs = []
    // n      , n+1      
    const len = sum[0].length + 1
    for (let i = 0; i < len; i ++) {
      sum.forEach((it) => {
  	    const t = it.slice()
        t.splice(i, 0, p)
        rs.push(t)
      })
    }
    return rs
  }, [])
)
// reduce       
[] + 1 
[[1]] + 2
[[2 1] [1 2]] + 3
[[3 2 1] [2 3 1] [2 1 3] [3 1 2] [1 3 2] [1 2 3]] + 4
// ...
//  、              
const a = [1, 2, 5, 9, 10]
const b = [3, 4, 6, 9, 10]

function findElement (a, b) {
    let i = j = 0
    while (i < a.length || j < b.length) {
        if (a[i] === b[j]) {
            return a[i]
        } else if (a[i] > b[j]) {
            j ++
        } else if (a[i] < b[j]) {
            i ++
        }
    }
    return null
}

console.log(findElement(a, b))
// => 9
//                    ,        。      ,    ,      。
//  、             
const data = [[1, 2, 5, 9, 10],
              [12, 22, 35, 49, 51],
              [61, 62, 75, 79, 81]]

const len = data[0].length
function findOffset (e, a, b) {
    if (a > b) return null 
    
    const offset = (b - a) / 2 + a

    //          
    const x = offset % len
    const y = ~~(offset / len)
    
    if (data[y][x] === e) {
        return [x, y]
    } else if (e > data[y][x]) {
        return findOffset(e, offset + 1, b)
    } else {
        return findOffset(e, a, offset - 1)
    }
}
findOffset(75, 0, len * data.length - 1)
// => [2, 2]

//                  indexOf    ,   data[0].length          ,           。
//          ,      ,                。