迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 如果元素不存在则使用Array.push() 添加

作者:迹忆客 最近更新:2023/02/07 浏览次数:

将不存在的元素压入数组:

  1. 使用 Array.includes() 方法检查该值是否存在于数组中。
  2. 如果值尚不存在,请使用 Array.push() 方法将值推送到数组中。
// ✅ With primitives
const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

if (!arr1.includes(value1)) {
  arr1.push(value1);
}

// -------------------------------------------

// ✅ With Objects
const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const index = arr2.findIndex(object => object.id === value2.id);

if (index === -1) {
  arr2.push(value2);
}

第一个示例中的数组包含原始值(字符串)。

我们使用逻辑 NOT ! 运算符来否定对 Array.includes() 方法的调用。

const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

console.log(arr1.includes(value1)); // 👉️ false

console.log(!arr1.includes(value1)); // 👉️ true

如果在数组中找到该值,则 Array.includes() 方法返回 true,否则返回 false。 如果该值不在数组中,我们将其推到数组的末尾。

const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

if (!arr1.includes(value1)) {
  arr1.push(value1);
}

// 👇️ [ 'a', 'b', 'c', 'd', 'e' ]
console.log(arr1);

在第二个示例中,我们有一个对象数组。

const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const index = arr2.findIndex(object => object.id === value2.id);

if (index === -1) {
  arr2.push(value2);
}

// 👇️ [ { id: 1 }, { id: 2 }, { id: 3 } ]
console.log(arr2);

我们使用 Array.findIndex() 方法获取数组中满足特定条件的第一个元素的索引。

在示例中,我们检查每个元素是否具有等于特定值的 id 属性。

const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const index = arr2.findIndex(object => object.id === value2.id);

console.log(index); // 👉️ -1

我们传递给 Array.findIndex() 方法的函数会针对数组中的每个元素进行调用,直到它返回真值或遍历整个数组。

如果从未满足条件,则 findIndex() 方法返回 -1,否则返回满足条件的第一个元素的索引。

const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const index = arr2.findIndex(object => object.id === value2.id);
console.log(index); // 👉️ -1

if (index === -1) {
  arr2.push(value2);
}

// 👇️ [{ id: 1 }, { id: 2 }, { id: 3 }]
console.log(arr2);

我们检查 findIndex() 方法是否在 if 语句中返回 -1。

如果是这样,我们就知道该值不存在于数组中,我们应该添加它。

在处理图元时,我们还可以使用 Array.indexOf() 方法。


Array.push() 元素如果不存在则使用 Array.indexOf()

将不存在的元素压入数组:

  1. 使用 Array.indexOf() 方法检查该值是否包含在数组中。
  2. 如果该值不包含在数组中,则 indexOf() 方法返回 -1
  3. 如果返回的索引为 -1,则将该值压入数组。
const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

if (arr1.indexOf(value1) === -1) {
  arr1.push(value1);
}

console.log(arr1); // 👉️ ['a','b','c','d','e']

我们使用 Array.indexOf() 方法代替 Array.includes()

请注意 ,如果数组包含对象,这将不起作用。 在这种情况下,我们应该使用前面示例中的 findIndex() 方法。

Array.indexOf() 方法获取一个值并检查它是否存在于数组中。 如果找到该值,则该方法返回其第一次出现的索引,否则返回 -1。

我们的 if 语句检查是否在数组中找不到该值并将其添加。

const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

if (arr1.indexOf(value1) === -1) {
  arr1.push(value1);
}

console.log(arr1); // 👉️ ['a','b','c','d','e']

我更喜欢使用 Array.includes() 方法,因为它更易于阅读且更直观。 我不必考虑该方法的实现细节以及它是否像 indexOf() 那样返回 -1。

或者,大家可以使用 Array.find() 方法。


Array.push() 元素如果不存在则使用 Array.find()

将不存在的元素压入数组:

  1. 使用 Array.find() 方法迭代数组。
  2. 在每次迭代中,检查数组中是否存在指定的值。
  3. 如果 Array.find() 方法返回 undefined,则将该值压入数组。
const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const object = arr2.find(object => {
  return object.id === value2.id;
});

console.log(object); // 👉️ undefined

if (object === undefined) {
  arr2.push(value2);
}

// 👇️ [ { id: 1 }, { id: 2 }, { id: 3 } ]
console.log(arr2);

我们传递给 Array.find() 方法的函数会针对数组中的每个元素(对象)进行调用。

在每次迭代中,我们检查当前对象是否有一个 id 属性,其值等于要添加的对象的 id 属性。

如果 Array.find() 方法返回 true,它会短路返回匹配的数组元素。如果从未满足条件,则 Array.find() 方法返回 undefined

我们的 if 语句检查 Array.find() 方法的返回值是否等于 undefined

如果满足条件,我们将对象推入数组。


如果 JavaScript 中不存在,则创建一个数组

如果数组不存在则创建一个数组:

  1. 检查变量的类型是否等于 undefined 或者变量是否不是数组。
  2. 如果满足任一条件,则将变量初始化为数组。
if (typeof arr === 'undefined' || !Array.isArray(arr)) {
  var arr = [];
}

console.log(arr); // 👉️ [];

我们首先检查变量 arr 是否具有未定义的类型。

即使尚未声明变量,typeof 运算符也不会抛出错误。

如果变量 arr 的类型为未定义,我们知道我们必须创建数组。

我们使用了逻辑或 || 运算符添加另一个条件。 如果运行运算符右侧的代码,我们就知道声明了 arr 变量。

在第二种情况下,我们检查变量是否不是数组类型。

如果变量是一个数组,我们不想重新创建它。 但是,如果它不是数组,我们会在 if 块中将其初始化为 1。

如果任一条件的计算结果为真,则 if 块运行,我们声明变量并将其设置为空数组。

请注意 ,我们有意使用 var 关键字而不是块作用域的 let 和 const。 这使得 arr 变量可以在 if 块之外访问。

如果我们之前使用 const 声明了 arr 变量,则此方法失败的唯一方法。

在这种情况下,我们将不允许重新声明一个已经声明的变量。

如果我们之前使用 let 声明了变量,则只需执行以下检查即可。

let arr;

if (!Array.isArray(arr)) {
  arr = [];
}

console.log(arr); // 👉️ [];

我们知道 arr 变量已经被声明,所以我们不必使用 typeof 运算符。

我们也没有使用 var 关键字。 如果它不是数组,我们所要做的就是更改 arr 变量的值。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便