Javascript - Tách mảng theo vị trí chẵn, lẻ

Tách mảng theo vị trí chẵn, lẻ

Viết mã JavaScript để chia một mảng các số nguyên dương đã cho thành hai phần. Vị trí lẻ vào 1 mảng, vị trí chẵn vào 1 mảng. Tính tổng 2 mảng và lưu vào 1 mảng.

Ví dụ:

JavaScript: Compute the sum of two parts and store into an array of size two.

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Compute the sum of two parts and store into an array of size two</title>
</head>
<script>
function alternate_Sums(arr) {
  var result = [0, 0];
  for(var i = 0; i < arr.length; i++) 
  {
    if(i % 2) result[1] += arr[i];
    else
      result[0] += arr[i];
  }
  return result
}

document.write(alternate_Sums([1, 3, 6, 2, 5, 10]))
</script>
<body>

</body>
</html>

Xem ví dụ

Lưu đồ thuật toán:

Flowchart: JavaScript - Compute the sum of two parts and store into an array of size two

 

 



Tư vấn lộ trình CNTT 🤖