Vue购物车案例和for...in与for...of的区别

html代码

  <div id="app">
    <div v-if="book.length">
      <table>
        <thead>
          <tr>
            <th></th>
            <th>书籍名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in book">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
            <td>{{item.price | showPrice}}</td>
            <td>
              <button @click="decreament(index)" :disabled="item.count <= 1">-</button> {{item.count}}
              <button @click="increament(index)">+</button>
            </td>
            <td><button @click="removeHandle">删除</button></td>
          </tr>
        </tbody>

      </table>
      <h2 style="margin: 0 auto;width: 200px;">总价:{{totalPrice|showPrice}}</h2>
    </div>
    <h2 v-else>空</h2>
  </div>

js代码

const app = new Vue({
  el: "#app",
  data: {
    book: [
      { id: 1, name: "围城", date: "2020.01.25", price: 88.00, count: 1, },
      { id: 2, name: "狂人日记", date: "2020.07.25", price: 58.00, count: 1, },
      { id: 3, name: "朝花夕拾", date: "2020.11.05", price: 85.00, count: 1, },
      { id: 4, name: "呐喊", date: "2020.05.05", price: 48.00, count: 1, }
    ],

  },
  computed: {

    totalPrice() {
      // 1.普通for循环
      //   let totalPrice = 0;
      //   for (let i = 0; i < this.book.length; i++) {
      //     totalPrice += this.book[i].price * this.book[i].count
      //   }
      //   return totalPrice;
      // }

      // 2.for...in 
      // 如果是对象的话得到的i是表示obj对象的每一个键值对的键
      //需要使用obj[i]来取到每一个值
      //数组的话输出就是索引但是是字符串的形式'0','1','2'
      // let totalPrice = 0
      // for (let i in this.book) {
      //   const book = this.book[i]
      //   totalPrice += book.price * book.count
      // }
      // return totalPrice;

      // 3.for...of 
      //for…of循环读取键值
      let totalPrice = 0
      for (let item of this.book) {
        totalPrice += item.price * item.count
      }
      return totalPrice
    }
  },
  methods: {
    increament(index) {
      this.book[index].count++
    },
    decreament(index) {
      // if (this.book[index].count > 1) {
      this.book[index].count--
   }//
    },
    removeHandle(index) {
      this.book.splice(index, 1)
    },

  },
  filters: {
    showPrice(price) {
      return "¥" + price.toFixed(2)
    }//设置价钱的标准格式
  }
})

<style>table{margin:0 auto}th{padding:14px 24px;background-color:#ccc}td{text-align:center}td button{margin:0 5px}</style>


for...in可以遍历数组或者对象,遍历时不仅能读取对象自身的属性或者手动加上的属性,还能延续原型链遍历出对象的原型属性,但是在某些情况下,for…in循环会以任意顺序遍历键名不会按照原有的顺序进行遍历。

for...of遍历的是数组或对象的value,如果要通过for…of循环,获取数组的索引,可以借助数组实例的entries方法和keys方法

所以尽量用for...in 遍历对象,for...of 可以用来遍历数组、类数组对象,字符串、Set、Map 以及 Generator 对象,不要用for...in遍历数组!

posted @ 2021-06-19 16:31  YokeF  阅读(132)  评论(0)    收藏  举报