arrays - Angular-数组forEach索引

标签 arrays angular foreach

如何在Angular4代码中为forEach循环标识索引。

我需要根据条件在foreach内拼接记录。

angular.forEach(myObject => {
    if(!myObject.Name)
        myObject.splice(..., 1)
};

如果myObject中的名称为空,我想在这里删除对象。

最佳答案

此处记录了forEach:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
语法:

arr.forEach(callback(currentValue[, index[, array]]) { // execute something }[, thisArg]);


参数:

callback: Function to execute on each element. It accepts between one and three arguments:


currentValue: The current element being processed in the array.


index: Optional, The index of currentValue in the array.


array: Optional, The array forEach() was called upon.


thisArg: Optional, Value to use as this when executing callback.


为了能够在此forEach循环中使用索引,可以通过以下方式添加索引:
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    name = 'Angular 6';

    myArray = [{name:"a"}, {name:""}, {name:"b"}, {name:"c"}];

    ngOnInit() {
        this.removeEmptyContent();
    }

    removeEmptyContent() {
        this.myArray.forEach( (currentValue, index) => {
          if(!currentValue.name){
              this.myArray.splice(index, 1);
          }
        });
    }
}
工作Stackblitz演示:
https://stackblitz.com/edit/hello-angular-6-g1m1dz?file=src/app/app.component.ts

关于arrays - Angular-数组forEach索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787477/

相关文章:

javascript - 类型 'auth'/home/kartik/Desktop/Ecommerce/ecommerce/node_modules/firebase/index") 上不存在属性 'typeof import("")'.ts(2339)

不同文件上的 Angular cli lint 错误导出

c# - string[].Foreach() 中的 T[] 参数

mysql - 为什么 MySQL 查询在 VB.net 中将整数列读取为字节数组?

Angular 2+ HTTP 请求 - 显示成功和错误响应的最短持续时间的加载微调器

mysql - 代表调用中心客户问题逻辑

scala - Spark 错误 :- "value foreach is not a member of Object"

php - PHP的 Assets 错误回显其他

Java:计算二维数组中的出现次数并输出一维数组中的结果

javascript - 更改数组值也会更改另一个指定数组中的值