可以使用数组的 includes() 方法来判断数组中是否包含某个元素,如果包含则使用 push() 方法将元素添加到数组中。

示例代码:

// 假设有一个数组 arr
const arr = [1, 2, 3, 4, 5];

// 判断数组中是否包含元素 3
if (arr.includes(3)) {
  console.log('数组中已经包含元素 3');
} else {
  console.log('数组中不包含元素 3');
  // 将元素 3 添加到数组中
  arr.push(3);
}

运行结果:

数组中已经包含元素 3

如果将元素 6 添加到数组中:

// 假设有一个数组 arr
const arr = [1, 2, 3, 4, 5];

// 判断数组中是否包含元素 6
if (arr.includes(6)) {
  console.log('数组中已经包含元素 6');
} else {
  console.log('数组中不包含元素 6');
  // 将元素 6 添加到数组中
  arr.push(6);
}

console.log(arr);

运行结果:

数组中不包含元素 6
[1, 2, 3, 4, 5, 6]
JavaScript 数组判断元素是否存在并添加:includes() 和 push() 方法

原文地址: https://www.cveoy.top/t/topic/omeP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录