JavaScript 数组去重:如何避免重复值添加
可以使用 Array.includes() 方法来判断数组中是否已经存在某个值,如果不存在则进行 Array.push() 操作。
以下是示例代码:
let arr = [1, 2, 3, 4, 5];
let value = 3;
if (!arr.includes(value)) {
arr.push(value);
} else {
console.log('Value already exists in the array.');
}
console.log(arr);
在上述代码中,如果数组 arr 中不存在值为 value 的元素,则将其 push 进数组中。如果已经存在,则输出提示信息'Value already exists in the array.',并且不进行 push 操作。
运行以上代码的输出结果将为:
Value already exists in the array.
[1, 2, 3, 4, 5]
原文地址: https://www.cveoy.top/t/topic/qeWp 著作权归作者所有。请勿转载和采集!