1:过滤掉不能被3整除的数,打印出来能被整除的数
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //过滤器filter let arr = [12, 33, 66, 99, 5] let result = arr.filter(item => { if (item % 3 == 0) { return true; } else { return false; } }) console.log(result) </script> </html>
打印结果如下:
或者这样写,效果是一样的
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> let arr = [11, 33, 66, 99, 5] let result = arr.filter(item => { return item % 3 == 0; }) console.log(result) </script> </html>
打印结果如下:
2:过滤商品价格小于10000元的商品,打印大于10000元的商品
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //商品列表 let arr = [{ title: '笔记本电脑', price: 12033 }, { title: '智能音箱', price: 99 }, { title: '鼠标', price: 33 }, { title: '单反摄像机', price: 20000 }, ] let result = arr.filter(item => item.price >= 10000); console.log(result) </script> </html>
打印结果如下: