Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
avaScript 在 ES6 上有很多數組方法,每種方法都有獨特的用途和好處。
在開發應用程序時,大多使用數組方法來獲取特定的值列表并獲取單個或多個匹配項。
在列出這兩種方法的區別之前,我們先來一一了解這些方法。
JavaScript find()方法
ES6 find() 方法返回通過測試函數的第一個元素的值。如果沒有值滿足測試函數,則返回 undefined。
語法
以下語法中使用的箭頭函數。
find((element) => { /* ... */ } )
find((element, index) => { /* ... */ } )
find((element, index, array) => { /* ... */ } )
我們有一個包含名稱 age 和 id 屬性的用戶對象列表,如下所示:
let users = [{
id:1,
name: 'John',
age: 22
}, {
id:2,
name: 'Tom',
age: 22
}, {
id:3,
name: 'Balaji',
age: 24
}];
以下代碼使用 find() 方法查找年齡大于 23 的第一個用戶。
console.log(users.find(user => user.age > 23));
//console
//{ id: 3, name: 'Balaji', age:24}
現在我們要找到第一個年齡為 22 的用戶
console.log(users.find(user => user.age === 22));
//console
//{ id: 1, name: 'John', age:22}
假設沒有找到匹配意味著它返回 undefined
console.log(users.find(user => user.age === 25));
//console
//undefined
JavaScript filter() 方法
filter() 方法創建一個包含所有通過測試函數的元素的新數組。如果沒有元素滿足測試函數,則返回一個空數組。
語法
filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )
我們將使用相同的用戶數組和測試函數作為過濾器示例。
以下代碼使用 filter() 方法查找年齡大于 23 的第一個用戶。
console.log(users.filter(user => user.age > 23));
//console
//[{ id: 3, name: 'Balaji', age:24}]
現在我們要過濾年齡為 22 歲的用戶
console.log(users.filter(user => user.age === 22));
//console
//[{ id: 1, name: 'John', age:22},{ id: 2, name: 'Tom', age:22}]
假設沒有找到匹配意味著它返回一個空數組
console.log(users.filter(user => user.age === 25));
//console
//[]
find() 和 filter() 的區別與共點
共點
高階函數:這兩個函數都是高階函數。
區別
1、通過一個測試功能
find() 返回第一個元素
filter() 返回一個包含所有通過測試函數的元素的新數組
2、如果沒有值滿足測試函數
find() 返回未定義
filter() 返回一個空數組
語法:
array.find(callback[, thisArg])
示例:
//查找大于3的元素
var arr = [1, 2, 3, 4, 5, 6];
var result = arr.find(item=> {
return item >= 3;
});
console.log(result); // 3
ython通過findAll('h4')獲取jin10網站的消息,jin10是一個財經資訊類網站
注意事項:本電腦環境是python 3.7
網頁爬取數據的步驟:
1、導入相應的模塊,例如request,BeautifulSoup等。 2、對網站進行請求 3、對網站HTML源代碼進行解析 4、嘗試打印所獲取的數據
代碼如下:
import requests from bs4 import BeautifulSoup import pandas as pd #1、網頁請求 url="https://www.jin10.com/" #設置請求網址為jin10網站 response=requests.get(url) #對金十財經網站進行get請求并將請求結果賦值給response response.encoding='utf-8' #設置網頁的編碼為'utf-8' html=response.text #獲取網頁的html源代碼并賦值給html #2、解析網站 #經查實發現所有的消息類信息都在h4標簽里,故去獲取h4標簽數據 soup=BeautifulSoup(html,'lxml') #解析html網頁的lxml代碼,并賦值給soup content=soup.findAll('h4') #查找網頁的h4標簽 #3、遍歷p標簽數據 for msg in content: #遍歷h4標簽的內容 print(msg.text) #打印h4標簽的內容,用text獲取數據
代碼運行結果如下圖所示:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。