[英]How to extract text from the following html as I want by JavaScript / cheerio?
[英]with JavaScript i want to have the following output
輸出一個數組,其中一個值與數組的下一個值相加。 最后一個值將與第一個值相加。
示例:[45, 4, 9, 16, 25] 轉換為:[49, 13, 25, 41, 70]
必須使用 Map() 方法。
您可以嘗試以下操作:
console.log([45, 4, 9, 16, 25].map((item, index, array) => item + array[(index + 1) % array.length]))
使用Array.prototype.map()
您可以使用 index 參數並在每次迭代中
看看它是否是數組的結尾,像這樣:
const arr = [45, 4, 9, 16, 25]; const newArr = arr.map((item, i) => { return i !== (arr.length - 1) ? item + arr[i + 1] : item + arr[0]; }) console.log(newArr);
這工作正常。
const nums = [45, 4, 9, 16, 25];
const newNums = nums.map((item, index) => {
if(index < nums.length - 1) {
return item + nums[ index + 1]
}
return item + nums[0]
})
console.log(newNums) // [ 49, 13, 25, 41, 70 ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.