测试代码
<template> <div class="container"> <span>This Test</span> </div> </template> <script> export default { name: "Test", data() { return { arr: [{ a: 111, b: 222 }, { c: 333, d: 444 }] } }, mounted() { console.log(this.arrfor()) console.log(this.arrforof()) this.arrfilter() this.arrsome() console.log(this.arrforeach()) console.log(this.arrmap()) console.log(this.arrfind()) }, methods: { arrfor() { var len = this.arr.length for (var j = 0; j < len; j++) { if (this.arr[j].a == 111) { return ‘arrfor success‘ } } }, arrforof() { for (var item of this.arr) { if (item.a == 111) { return ‘forof success‘ } } }, arrfilter() { console.log(this.arr.filter(item => { return item.c == 333 })) }, arrsome() { console.log(this.arr.some(item => { if (item.a == 111) { return ‘arrsome success‘ } })) }, arrforeach() { this.arr.forEach(item => { if (item.a == 111) { return ‘arrforeach success‘ } }) }, arrmap() { this.arr.map(item => { if (item.a == 111) { return ‘map success‘ } }) }, arrfind() { this.arr.find((item) => { item.a == 111 }) } }, } </script> <style scoped> </style>
测试结果
仅for和forof能正确return
filter返回新数组,判断结果为true则加入新数组,否则过滤
some返回true时跳出整个循环 ruturn 类型仅能为 Boolean
原文:https://www.cnblogs.com/xuanjiange/p/15306817.html