Hướng dẫn sum with javascript

Trong bài này freetuts sẽ hướng dẫn bạn giải bài tập tính tổng hai số bằng javascript, qua đó bạn có thể tự viết chương trình tính tổng cực kì dễ dàng.

Hướng dẫn sum with javascript

Hướng dẫn sum with javascript

Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Bài tập cộng 2 số là cơ bản nhất trong lập trình, bằng cách sử dụng toán tử cộng và kết hợp các hàm khác để tạo ra ứng dụng tính tổng. Tuy nhiên, bài này mình sẽ bổ sung thêm kiến thức nâng cao để những bạn có nền tảng rồi tham khảo nhé.

1. Tính tổng hai số bằng javascript đơn giản

Ví dụ 1: Cho hai biến a và b, hãy viết chương trình tính tổng hai số a và b rồi in lên trình duyệt.

https://freetuts.net/editor.html?id=1570

let a = 20;
let b = 30;

// Tính tổng
let tong = a + b;

document.write("Tổng hai số là: " + tong);

Ví dụ 2: Cho hai ô input textbox và 1 input button. Hãy viết chương trình khi click vào button thì tính tổng hai số ở hai ô input.

Bài viết này được đăng tại [free tuts .net]

function sum(){
    let a = Number(document.getElementById("num1").value);
    let b = Number(document.getElementById("num2").value);

    let sum = parseInt(a) + b;

    document.getElementById('result').innerHTML = sum;
}

Trong ví dụ này thì mình sử dụng hàm Number để ép kiểu string sang kiểu number.

Ví dụ 3: Tính tổng hai số trong object javascript

Giả sử mình có một object như sau:

let numbers = {
    number1 : 20,
    number2 : 30
};

Để tính tổng hai số number1 và number2 thì ta làm như sau:

let numbers = {
    number1 : 20,
    number2 : 30
};

let sum = numbers.number1 + numbers.number2; // 50

2. Kiểm tra dữ liệu trước khi tính tổng bằng javascript

Khi lấy dữ liệu từ người dùng thì bạn phải kiểm tra định dạng dữ liệu trước rồi mới tính toán sau. Bước này giúp chương trình không bị lỗi và đảm bảo ứng dụng không bị dừng đột ngột.

Đối với bài tập tính tổng hai số trong js này thì ta chỉ cần chắc chắn rằng hai số mà người dùng nhập vào là number. Vì vậy, bạn chỉ cần áp dụng kỹ thuật ép kiểu dữ liệu trong javascript và lệnh if else là có thể xử lý được.

function sum(){
    let a = document.getElementById("num1").value;
    let b = document.getElementById("num2").value;

    // Kiểm tra dữ liệu
    if (a == "" || b == ""){
        alert("Vui lòng nhập vào hai số");
        return false;
    }

    // Ép kiểu dữ liệu
    a = Number(a);
    b = Number(b);

    if (isNaN(a) || isNaN(b)){
        alert("Bạn phải nhập vào hai số");
        return false;
    }

    let sum = parseInt(a) + b;

    document.getElementById('result').innerHTML = sum;
}

3. Viết hàm cộng hai số bằng javascript

Để cho bài toán đơn giản hơn thì ta sẽ viết một hàm cộng hai số. Mình sẽ viết nhiều hàm, từ đơn giản đến phức tạp để các bạn dễ hiểu hơn.

Hàm 1: Không validate dữ liệu.

function sum(a, b){
    return a + b;
}

// Hoặc dùng arrow function
let sum = (a, b) => {
    return a + b;
};

Hàm 2: Có validate dữ liệu

function sum(a, b){
    a = Number(a);
    b = Number(b);
    if (isNaN(a) || isNaN(b)){
        return false;
    }
    return a + b;
}

// Hoặc dùng arrow function
let sum = (a, b) => {
    a = Number(a);
    b = Number(b);
    if (isNaN(a) || isNaN(b)){
        return false;
    }
    return a + b;
};

Hàm 3: Kết hợp try catch javascript để bắt lỗi.

function sum(a, b){
    try{
        a = Number(a);
        b = Number(b);
        if (isNaN(a) || isNaN(b)){
            throw new Error('Dữ liệu bạn nhập vào không phải là số');
        }
        return a + b;
    }
    catch (e){
        console.log(e.message);
        return false;
    }
}

Trên là tất cả những cách cộng hai số trong javascript nói chung và bài tập tính tổng hai số bằng javascript nói riêng.

Just another take, this is what native JavaScript functions Map and Reduce were built for (Map and Reduce are powerhouses in many languages).

var traveler = [{description: 'Senior', Amount: 50},
                {description: 'Senior', Amount: 50},
                {description: 'Adult', Amount: 75},
                {description: 'Child', Amount: 35},
                {description: 'Infant', Amount: 25}];

function amount(item){
  return item.Amount;
}

function sum(prev, next){
  return prev + next;
}

traveler.map(amount).reduce(sum);
// => 235;

// or use arrow functions
traveler.map(item => item.Amount).reduce((prev, next) => prev + next);

Note: by making separate smaller functions we get the ability to use them again.

// Example of reuse.
// Get only Amounts greater than 0;

// Also, while using Javascript, stick with camelCase.
// If you do decide to go against the standards, 
// then maintain your decision with all keys as in...

// { description: 'Senior', Amount: 50 }

// would be

// { Description: 'Senior', Amount: 50 };

var travelers = [{description: 'Senior', amount: 50},
                {description: 'Senior', amount: 50},
                {description: 'Adult', amount: 75},
                {description: 'Child', amount: 35},
                {description: 'Infant', amount: 0 }];

// Directly above Travelers array I changed "Amount" to "amount" to match standards.

function amount(item){
  return item.amount;
}

travelers.filter(amount);
// => [{description: 'Senior', amount: 50},
//     {description: 'Senior', amount: 50},
//     {description: 'Adult', amount: 75},
//     {description: 'Child', amount: 35}];
//     Does not include "Infant" as 0 is falsey.

Sum a Property in an Array of Objects in JavaScript #

To sum a property in an array of objects:

  1. Call the reduce() method to iterate over the array.
  2. On each iteration increment the sum with the specific value.
  3. The result will contain the sum of the values for the specific property.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; const sum = arr.reduce((accumulator, object) => { return accumulator + object.salary; }, 0); console.log(sum); // 👉️ 60

The function we passed to the Array.reduce() method gets invoked with each element (object) in the array.

The accumulator parameter gets an initial value of 0 because that's what we supplied as the second argument to the reduce method.

We increment the accumulator by the value of the salary property for each object in the array.

The reduce method returns the sum of the salary values of all objects in the array.

An alternative and perhaps simpler approach is to use the forEach method.

To sum a property in an array of objects:

  1. Initialize a sum variable, using the let keyword and set it to 0.
  2. Call the forEach() method to iterate over the array.
  3. On each iteration, increment the sum variable with the value of the object.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; arr.forEach(element => { sum += element.salary; }); console.log(sum); // 👉️ 60

The function we passed to the Array.forEach method gets called with each element in the array.

Notice that we declared the sum variable using the let keyword. We can't reassign variables declared using const.

On each iteration of the loop, we increment the value stored in the sum variable to get the total amount.

This approach is more readable and intuitive, especially if you're not used to how the reduce method works.

You can also achieve the same result by using a basic for loop.

Copied!

const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index].salary; } console.log(sum); // 👉️ 60

This code snippet achieves the same goal, however instead of the forEach method, we use a basic for loop.

Instead of accessing the element directly, we have to use the index of each iteration.

This is a bit indirect and cluttered, however most developers are used to reading for loops.