js技术之“向数组添加元素”

一、js中对于数组[]的操作很常见

下面记录一下js向数组添加元素的方法

   const array=[1,2,3];

    console.log('原数组:',array);

 

效果图

 

 

 

二、用push在数组后面插入元素

   array.push(4,5);
    console.log('用push在数组后面插入元素:',array);

 

效果图

 

 

 

三、用unshift在数组前面插入元素

    array.unshift(6,7);

    console.log('用unshift在数组前面插入元素:',array);

 

效果图

 

 

四、用splice在数组指定位置插入元素

   array.splice(2,0,'小可爱');
console.log(
'用splice在数组指定位置插入元素:',array);

 

效果图

 

 

五、数组循环,根据值获取map的value,然后复制给新的数组

        const departmentTypeName = [];
        this.productLabel.departmentTypes
                .forEach(item => departmentTypeName.push(this.dataSource.departmentTypeMap[item]))
        this.productLabel.departmentTypeName = departmentTypeName

 

posted @ 2022-07-19 18:59  骚哥  阅读(1249)  评论(0编辑  收藏  举报