题解 | #添加元素#

添加元素

http://www.nowcoder.com/practice/3c7905cea3264ddaac4bf637ab3a19f9

/* 1.使用for循环和push方法 */
function append(arr, item) {
    const res = []
    for(let i=0;i<arr.length;i++) {
        res.push(arr[i])
    }
    res.push(item)

    return res;
}

/* 2.使用concat合并 */
function append(arr, item) {

    return arr.concat(item);
}

/* 3.使用slice浅拷贝数组 */
function append(arr,item) {
    let res = arr.slice(0)
    res.push(item)
    return res
}

/* 4.使用扩展运算符 */
function append(arr,item) {
    let res = [...arr,item]
    return res
}

/* 5.forEach替代for循环 */
function append(arr, item) {
    const res = []
    arr.forEach(element => {
        res.push(element)
    });
    res.push(item)

    return res;
}

全部评论
slice 应该是深拷贝
1 回复 分享
发布于 2021-08-04 17:34
使用扩展运算符返回的是对象类型,而要求的是新数组类型,我觉得严格来说不行吧
点赞 回复 分享
发布于 2022-05-26 18:39
concat是字符串对象的方法,不是数组对象
点赞 回复 分享
发布于 2021-08-23 11:19

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
57
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务