使用find方法为TypeScript中的所有元素更改类数组属性值。

5 浏览
0 Comments

使用find方法为TypeScript中的所有元素更改类数组属性值。

我有下面的示例代码:

let arr = [
{ name:"string 1", value:"value1", other: "other1" },
{ name:"string 2", value:"value2", other: "other2" }
];
let obj = arr.find((o, i) => {
       arr[i] = { name: 'new name', value: 'new value', other: 'that' };
    return true; // 停止搜索
});
  console.log(arr);

我想将所有数组值替换为名称为"new name"和值为"new value"的值,现在它只更改第一个数组索引值。

0
0 Comments

问题的出现原因:

问题是由于需要对数组中的每个元素的属性进行修改,但是使用forEach方法时,无法直接返回修改后的数组。

解决方法:

可以使用find方法来实现对数组中所有元素的属性值进行修改。

以下是解决问题的代码示例:

class ArrayPropertyChange {
  arr: { name: string; value: string; other: string }[];
  constructor() {
    this.arr = [
      { name: "string 1", value: "value1", other: "other1" },
      { name: "string 2", value: "value2", other: "other2" },
    ];
  }
  changeProperties() {
    this.arr = this.arr.map((element) => {
      element.name = "new name";
      element.value = "new value";
      element.other = "that";
      return element;
    });
    console.log(this.arr);
  }
}
const arrayPropertyChange = new ArrayPropertyChange();
arrayPropertyChange.changeProperties();

运行以上代码,可以看到控制台输出了修改后的数组。

通过使用find方法,我们可以对数组中的每个元素进行属性值的修改,并且直接返回修改后的数组。这样就实现了对所有元素的属性值进行修改的需求。

0
0 Comments

使用find()方法时返回的是数组中满足条件的第一个元素。在你的函数中返回true,所以在找到第一个索引后就停止迭代。

当你需要将数组中的每个值都改变为新值时,应该使用map()方法。从map()函数中返回一个对象。首先使用扩展运算符...将对象的所有属性复制到最终对象中,然后将所需的属性设置为新值。

let arr = [
  { name:"string 1", value:"value1", other: "other1" },
  { name:"string 2", value:"value2", other: "other2" }
];
const res = arr.map(x => ({...x, name: "new name", value: "new value"}))
console.log(res)

欢迎您。在开始项目之前最好阅读一些关于数组方法的文档,特别是迭代方法。这将对您有很大帮助。您可以在此处获取一个列表:[developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)

还有一个问题,如果我们需要根据条件更改值,如何应用过滤器。

this.state.formOrderItems.map(x => (x.id === ev ? { ...x, isDefault: checked } : x

以上方法有什么问题吗?

没有问题,但是我需要根据条件过滤数据。

您需要使用Array.prototype.filter方法。

0