开发者问题收集

如何从数组中删除对象?

2018-01-15
86

我有这个数组,我必须将对象推送到数组中。但现在我正试图摆脱“cahlan”的整个对象。底部的 for 循环是我尝试过的,但它似乎不起作用。

var employees = [];

var tyler = {
  name: 'Tyler',
  position: 'Lead Instructor/Engineer',
  spiritAnimal: 'Honey Badger'
};

var cahlan = {
  name: 'Cahlan',
  position: 'CEO',
  spiritAnimal: 'butterfly'
};

var ryan = {
  name: 'Ryan',
  position: 'Marketing',
  spiritAnimal: 'fox'
};

var colt = {
  name: 'Colt',
  position: 'Everything really',
  spiritAnimal: 'Young Male Horse'
};

employees.push("tyler", "cahlan", "ryan", "colt");

for (var i = 0; i < employees.length; i++) {
  if (employees[i].name === "Cahlan") {
    employees.splice(i);
  }
}
3个回答
var employees = [];

employees.push("tyler", "cahlan", "ryan", "colt");

for (var i = 0; i < employees.length; i++) {
  if (employees[i] === "cahlan") {
     employees.splice(i, 1);
     break;
  }
}

console.log(employees)

两件事:

  • 您正在与大写单词 Cahlan 进行比较。
  • employees 数组中的对象是字符串,因此,属性 name 不存在。

您可能没有意识到,但您没有添加已初始化的对象,因此,数组正在使用字符串初始化。

Ele
2018-01-15

您的解决方案正朝着正确的方向发展,但您犯了两个错误。

首先,

employees.push("tyler", "cahlan", "ryan", "colt");

不会像您期望的那样将对象推送到数组中。它将字符串推送到仅包含对象变量名称的 employees 中。JavaScript 不知道您正在尝试引用这些对象。它认为您只是在创建一些文本。为了正确起见,请删除双引号:

employees.push(tyler, cahlan, ryan, colt);

您始终可以通过将数组内容打印到控制台来检查它的内容:

console.log(employees);

其次,您需要将第二个参数传递给 splice ,告诉它要从数组中删除多少个项目。由于您只想删除一个项目,请执行以下操作:

employees.splice(i, 1);

完整解决方案:

var employees = [];

var tyler = {
  name: 'Tyler',
  position: 'Lead Instructor/Engineer',
  spiritAnimal: 'Honey Badger'
};

var cahlan = {
  name: 'Cahlan',
  position: 'CEO',
  spiritAnimal: 'butterfly'
};

var ryan = {
  name: 'Ryan',
  position: 'Marketing',
  spiritAnimal: 'fox'
};

var colt = {
  name: 'Colt',
  position: 'Everything really',
  spiritAnimal: 'Young Male Horse'
};

employees.push(tyler, cahlan, ryan, colt); // 1.) remove double quotes

console.log(employees); // print array to console to check if array is setup right

for (var i = 0; i < employees.length; i++) {
  if (employees[i].name === "Cahlan") {
    employees.splice(i, 1); // 2.) add second paramter
  }
}

console.log(employees); // print array again to see if removing worked
Niklas Gruhn
2018-01-15

纯 javascript:

var ret = [];

for (var i = 0; i < employees.length; i++) {
  if (employees[i].name !== "Cahlan") ret.push(employees[i]);
}

//ret has the employees with Cahlan removed.

使用 Jquery:

employees = $.grep(employees, function(a)) {
  return a.name !== "Cahlan";
});

您应该先进行更多搜索。请参阅 remove-object-from-array-using-javascript

Cemal
2018-01-15