We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
@FishPlusOrange
有赞
一面
在不改变原数组的前提下,向该数组的首位添加一个新的元素,得到一个新数组,你能想到的方法有哪些呢
同样的前提条件下,删除该数组的最后一个元素,得到一个新数组,你能想到的方法有哪些呢
The text was updated successfully, but these errors were encountered:
答案:
在不改变原数组的前提下,向该数组的首位添加一个新的元素,得到一个新数组,假设新增元素为0:
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]
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 在使用的时候会对原数组造成影响,简单归纳一下:
不修改原数组
forEach
map
every
some
filter
reduceRight
keys
values
entries
includes
find
findIndex
flat
flatMap
修改原数组
splice
pop
push
shift
unshift
sort
reverse
fill
copyWithin
Sorry, something went wrong.
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)
FishPlusOrange
No branches or pull requests
To:
@FishPlusOrange
面试公司:
有赞
面试环节:
一面
问题:
在不改变原数组的前提下,向该数组的首位添加一个新的元素,得到一个新数组,你能想到的方法有哪些呢
同样的前提条件下,删除该数组的最后一个元素,得到一个新数组,你能想到的方法有哪些呢
The text was updated successfully, but these errors were encountered: