目录

方式1:splice(index,1)

方式2:new Set() .delete()

方式3:delete


 

方式1:splice(index,1)

splice() 方法会直接对修改原数组

    let arr = ["vue", "react", "angular"];
    console.log("删除前arr:", arr);
    for (let i in arr) {
      if (arr[i] === "react") {
        let result = arr.splice(i, 1);
        console.log("删除值:", result);
      }
    }
    console.log("删除后arr:", arr);

方式2:new Set() .delete()

    let arr = ["vue", "react", "angular"];
    console.log("删除前arr:", arr);

    let setArr = new Set(arr);
    let result = setArr.delete("react");

    console.log("是否删除成功:", result);
    console.log("删除后arr:", Array.from(setArr));

方式3:delete

delete删除掉数组中的元素后,会把该下标出的值置为undefined,数组的长度不会变

    let arr = ["vue", "react", "angular"];
    console.log("删除前arr:", arr);

    let result = delete arr[1];

    console.log("是否删除成功:", result);
    console.log("arr[1]:", arr[1]);
    console.log("删除后arr:", arr);

 

Logo

前往低代码交流专区

更多推荐