The forEach() method performs the provided function once on each element of the array

Blog.csdn.net/ZhengKehang…

How to rewrite [1,2,3] to [2,2,2] with forEach

Wrong usage

[1.2.3].forEach(item= >{
       item=2
   })
Copy the code

Why not?

Since each item in [1,2, and 3] has a primitive data type, this creates a new space on the stack item:2

 [1.2.3].forEach((item,index,self) = >{
      self[index]=2  // Because we changed the value of the array object
   })
Copy the code

Other uses for loop, map, etc

[1.2.3].map(item= > 3)
Copy the code

If you want to change a property of an object in data in a responsive manner, the property must be declared in the object in advance. So we don’t listen for primitive types in arrays.

    new Vue({
        el: '#app'.data() {
            return {
                arr: [1.1]}},create() {
            this.arr.forEach((item, index, self) = > {
                self[index] = 2})}})Copy the code

Proper use

    new Vue({
        el: '#app'.data() {
            return {
                arr: [1.1]}},create() {
            this.arr.forEach((item, index, self) = > {
                this.$set(this.arr, index, 2)})}})Copy the code

ForEach Other precautions Note: The above only for… Of terminates the loop with break