React数组工具函数

本小妞迷上赌 提交于 2019-12-05 23:10:59
//数组操作工具函数:arrayUtils都是产生新的array,而不是操作源array
let arrayUtils = {
    /**
     * 在指定索引位置增加新元素,未指定index时添加到最后面
     * @param array (array)
     * @param newItem   (object)
     * @param index (int)
     * @returns {*} 返回新数组
     */
    addItem: (array, newItem, index) => {
        if(typeof index !== 'undefined'){
            return [
                ...array.slice(0, index),
                newItem,
                ...array.slice(index + 1)
            ]
        }else{
            return [
                ...array,
                newItem
            ];
        }
    },
    /**
     * 删除指定id的元素
     * @param array
     * @param id
     * @returns {[*,*]} 返回新数组
     */
    delItem: (array, id) => {
        const findIndex = array.findIndex(item => item.id == id);

        return [
            ...array.slice(0, findIndex),
            ...array.slice(findIndex + 1)
        ];
    },
    /**
     * 替换数组中指定的元素
     * @param array
     * @param id    
     * @param newItem (object)
     * @returns {[*,*,*]} 返回新数组
     */
    modifyItem: (array, id, newItem) => {
        const findIndex = array.findIndex(item => item.id == id);

        return [
            ...array.slice(0, findIndex),
            {
                ...array[findIndex],
                ...newItem
            },
            ...array.slice(findIndex + 1)
        ];
    }
};

  

转载于:https://www.cnblogs.com/nankeyimeng/p/7235376.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!