简体   繁体   English

对于未知数量的元素,尝试将数组的每个元素添加到下一个元素

[英]Trying to add each element of array to the next one for unknown number of elements

Something like this but generalized像这样但很笼统

let arr = [6, 5, 4, 3];
let i = 0, j = 0;
let result = [];

    result.push(arr[0]+arr[1],
arr[2]+arr[3]);

console.log(result

Ignoring last element if array has odd number of elements:如果数组有奇数个元素,则忽略最后一个元素:

 function f(arr) { let result = []; for (let i=0; i<arr.length; i++) { if (i % 2==0 && i<arr.length-1) { result.push(arr[i] + arr[i+1]); i++; } }; return result; } let arr = [6, 5, 4, 3]; console.log(f(arr)); console.log(f([1, 2, 3, 4, 5, 6, 7]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算要在一个屏幕上显示的元素的宽度和高度,元素数量未知 - Calculating width and height of an element to be on one screen, unknown number of elements 单击按钮将元素添加到 javascript 中的数组时,每次 console.logging 返回数组时都会少一个元素 - On clicking a button to add elements to an array in javascript, each time console.logging the array is returned with one less element 如何使用javascript或angular将一个数组的每个元素添加到其他数组中的对应元素 - How can I add each element of one array to corresponding elements in other arrays with javascript or angular 如何将边距设置为相邻的两个元素中的一个元素? - How can I set margin to one element of two elements which are next to each other? 试图将数组的元素添加到一起 - Trying to add elements of an array together 将元素添加到数组并打印元素 - Add element to array and print the elements 用数组的一个元素查找元素 - Find elements with one element of array JavaScript:将偶数元素的和添加到给定数组中的每个奇数值元素; 显示新数组 - JavaScript: Add sum of even value elements to each odd value element in an given array; show the new array 如何迭代 HTML 数组<div>元素并为每个索引号对另一个元素设置不同的样式? - How to iterate an array of HTML <div> elements and style another element differently for each index number? 包含一个元素的数组包含许多我想成为数组元素的对象 - Array containing one element containing a number of objects which I'd like to be elements of array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM