![](/img/trans.png)
[英]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.