如何在vueJs中使用forEach?

How to use forEach in vueJs?

我收到来自 API 电话的如下回复,

现在,我必须在数组中重复整个数组。我如何在 VueJS 中做到这一点?

我已经搜索过使用 forEach.. 没有找到像键|值对这样的 forEach 用法。

任何人都可以帮助我了解如何使用 forEach 或任何其他 (VueJS) 从数组中获取值吗?

感谢和问候,

VueJS 中,您可以像下面那样使用 forEach

let list=[];
$.each(response.data.message, function(key, value) {
     list.push(key);
   });

所以,现在您可以将所有数组放入 list 中。使用 for 循环获取值或键

您还可以将 .map() 用作:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

这是 forEach 用法的示例:

let arr = [];

this.myArray.forEach((value, index) => {
    arr.push(value);
    console.log(value);
    console.log(index);
});

在这种情况下,"myArray" 是我数据中的一个数组。

您也可以使用 filter 遍历数组,但是如果您想获得一个 new list数组的过滤元素。

像这样:

const newArray = this.myArray.filter((value, index) => {
    console.log(value);
    console.log(index);
    if (value > 5) return true;
});

同样可以写成:

const newArray = this.myArray.filter((value, index) => value > 5);

filter 和 forEach 都是 javascript 方法,可以很好地与 VueJs 一起使用。此外,看看这个可能会很有趣:

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

您可以使用本机 javascript 函数

var obj = {a:1,b:2};

Object.keys(obj).forEach(function(key){
    console.log(key, obj[el])
})

或者为每个对象创建一个对象原型,但这通常会导致其他框架出现问题

if (!Object.prototype.forEach) {
  Object.defineProperty(Object.prototype, 'forEach', {
    value: function (callback, thisArg) {
      if (this == null) {
        throw new TypeError('Not an object');
      }
      thisArg = thisArg || window;
      for (var key in this) {
        if (this.hasOwnProperty(key)) {
          callback.call(thisArg, this[key], key, this);
        }
      }
    }
  });
}

var obj = {a:1,b:2};

obj.forEach(function(key, value){
    console.log(key, value)
})


您需要的关键字是展平数组。现代 javascript 数组带有 flat method. You can use third party libraries like underscorejs 以防您需要支持旧浏览器。

原生示例:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

下划线示例:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

在 VueJS 中,您可以像这样遍历数组: const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

在我的例子中,我想遍历文件并将它们的类型添加到另一个数组:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }