本文介绍了Angular - 每个索引的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何识别 Angular4 代码中 forEach 循环的索引.

我需要根据条件拼接foreach里面的记录.

angular.forEach(myObject => {如果(!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]]) {//执行某事}[, thisArg]);

参数:

回调:在每个元素上执行的函数.它接受一到三个参数:

currentValue: 数组中正在处理的当前元素.

索引: 可选,数组中currentValue的索引.

数组: 可选,调用了数组 forEach().

thisArg: 可选,执行回调时用作 this 的值.

为了能够在这个 forEach 循环中使用索引,你可以这样添加索引:

import { Component } from '@angular/core';@零件({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {name = 'Angular 6';myArray = [{name:"a"}, {name:""}, {name:"b"}, {name:"c"}];ngOnInit() {this.removeEmptyContent();}removeEmptyContent() {this.myArray.forEach((currentValue, index) => {如果(!currentValue.name){this.myArray.splice(index, 1);}});}}

正在运行的 Stackblitz 演示:

https://stackblitz.com/edit/hello-angular-6-g1m1dz?file=src/app/app.component.ts

How to identify the index for the forEach loop in the Angular4 code.

I need to splice the record inside the foreach based on the condition.

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

Here I want to delete the object if the name in myObject is blank.

解决方案

forEach is documented here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Syntax:

Parameters:

To be able to use an index inside this forEach loop, you can add an index this way:

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);
          }
        });
    }
}

Working Stackblitz demo:

https://stackblitz.com/edit/hello-angular-6-g1m1dz?file=src/app/app.component.ts

这篇关于Angular - 每个索引的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:20