不用 + eval Function 实现加法

You're asking how to implement addition in frontend JavaScript without using the eval() function. Here are a few ways:

1. Using the + operator (for numbers):

This is the standard and most straightforward way to add numbers in JavaScript. Make sure your operands are actually numbers and not strings, otherwise, you'll get string concatenation.

let num1 = 10;
let num2 = 5;
let sum = num1 + num2; // sum will be 15

// Handle potential string inputs:
let str1 = "10";
let str2 = "5";
let sum2 = Number(str1) + Number(str2); // Convert to numbers before adding
// Or
let sum3 = parseInt(str1) + parseInt(str2); // parseInt for integers
// Or
let sum4 = parseFloat(str1) + parseFloat(str2); // parseFloat for floating-point numbers


console.log(sum);  // Output: 15
console.log(sum2); // Output: 15
console.log(sum3); // Output: 15
console.log(sum4); // Output: 15

2. Bitwise Operators (for integers):

While less common for simple addition, you can use bitwise operators. This approach is generally more complex and less readable for straightforward addition but can be useful in specific performance-critical scenarios or when working with bitwise representations. Here's a basic example (note limitations with handling negative numbers directly):

function add(x, y) {
  while (y != 0) {
    let carry = x & y;  // Calculate the carry bits
    x = x ^ y;          // XOR gives the sum without carry
    y = carry << 1;     // Shift carry bits to the left
  }
  return x;
}

console.log(add(10, 5)); // Output: 15

3. Reduce Function (for arrays of numbers):

If you have an array of numbers you want to sum, the reduce() method is a good option:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 0 is the initial value of the accumulator

console.log(sum); // Output: 15

It's crucial to avoid eval() unless absolutely necessary due to security risks (potential for arbitrary code execution) and performance overhead. The methods above provide safe and efficient ways to perform addition in JavaScript. Choose the method that best suits your specific needs and context. For simple addition of numbers, the + operator is the most straightforward and recommended approach. Remember to handle string inputs appropriately by converting them to numbers first.

posted @   王铁柱6  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示