Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

有赞: 在不改变原数组的前提下,添加或删除某个元素(一面) #16

Open
FishPlusOrange opened this issue Apr 30, 2019 · 2 comments

Comments

@FishPlusOrange
Copy link
Member

FishPlusOrange commented Apr 30, 2019

To:

@FishPlusOrange

面试公司:

有赞

面试环节:

一面

问题:

在不改变原数组的前提下,向该数组的首位添加一个新的元素,得到一个新数组,你能想到的方法有哪些呢

同样的前提条件下,删除该数组的最后一个元素,得到一个新数组,你能想到的方法有哪些呢

@FishPlusOrange FishPlusOrange changed the title To FishPlusOrange: 在不改变原数组的前提下,添加或删除该数组的某个元素(有赞) To FishPlusOrange: 在不改变原数组的前提下,添加或删除某个元素(有赞) Apr 30, 2019
@FishPlusOrange
Copy link
Member Author

答案:

在不改变原数组的前提下,向该数组的首位添加一个新的元素,得到一个新数组,假设新增元素为0

  • concat
let arr = [1, 2, 3, 4]
let newArr = [].concat(0, arr)
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [0, 1, 2, 3, 4]
  • 扩展运算符
let arr = [1, 2, 3, 4]
, newArr = [0, ...arr]
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [0, 1, 2, 3, 4]
  • reduce
let arr = [1, 2, 3, 4]
, newArr = arr.reduce((acc, cur) => {
  acc.push(cur)
  return acc
}, [0])
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [0, 1, 2, 3, 4]

同样的前提条件下,删除该数组的最后一个元素,得到一个新数组:

  • slice
let arr = [1, 2, 3, 4]
, newArr = arr.slice(0, -1)
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [1, 2, 3]
  • reduce
let arr = [1, 2, 3, 4]
, last = arr.length - 1
, newArr = arr.reduce((acc, cur, idx) => {
  if (idx !== last) {
    acc.push(cur)
  }
  return acc
}, [])
console.log(arr) // [1, 2, 3, 4]
console.log(newArr) // [1, 2, 3]

解答思路:

这道题主要考察数组相关操作,包括一些数组 API 的使用。

我们需要清楚哪些 API 不会修改原数组,哪些 API 在使用的时候会对原数组造成影响,简单归纳一下:

  • 不修改原数组

    • slice
    • concat
    • forEach
    • map
    • every
    • some
    • filter
    • reduce
    • reduceRight
    • keys
    • values
    • entries
    • includes
    • find
    • findIndex
    • flat
    • flatMap
  • 修改原数组

    • splice
    • pop
    • push
    • shift
    • unshift
    • sort
    • reverse
    • fill
    • copyWithin

@acodercc acodercc added this to the 已回答 milestone Apr 30, 2019
@acodercc acodercc changed the title To FishPlusOrange: 在不改变原数组的前提下,添加或删除某个元素(有赞) 有赞: 在不改变原数组的前提下,添加或删除某个元素(一面) May 6, 2019
@Seasonley
Copy link

  • Array.from
let arr = [1, 2, 3, 4]
var res=Array.from(arr)
res.splice(0,1)
console.log(res)
  • Array.prototype.filter
let arr = [1, 2, 3, 4]
res=arr.filter((v,i) => i > 0)
console.log(res)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants