首页 > 其他分享 >不用 + eval Function 实现加法

不用 + eval Function 实现加法

时间:2024-12-07 09:58:55浏览次数:6  
标签:Function 15 log sum let numbers eval 加法 console

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.

标签:Function,15,log,sum,let,numbers,eval,加法,console
From: https://www.cnblogs.com/ai888/p/18591834

相关文章

  • 调用matlab用户自定义的function函数时,有多个输出变量只输出第一个变量
        很多朋友在使用matlab时,会使用或自己编辑多个function函数,来满足自己对任务处理的要求,但是在调用function函数时,会出现这个问题:调用matlab用户自定义的function函数时,有多个输出变量只输出第一个变量。    假设我定义的function函数代码如下:function[a,......
  • vue3 使用 inject provide 提供全局变量 报错 [Vue warn]: inject() can only be used
    报错:vue3使用injectprovide提供全局变量报错[Vuewarn]:inject()canonlybeusedinsidesetup()orfunctionalfunctionalcomponents.场景main.js//main.js使用provide提供全局变量,做图片的urlapp.provide('imgurl','http://api.baidu.com/')pro.js......
  • 在易优CMS中遇到“Call to undefined function think\exception\config()”错误时,应
    在使用易优CMS时,如果你遇到了“Calltoundefinedfunctionthink\exception\config()”这样的错误提示,这通常意味着系统在尝试调用一个未定义的函数。这种错误可能是由多种原因引起的,但最常见的原因是数据库连接问题。以下是一些详细的解决步骤和建议:检查数据库连接确认数据......
  • 随笔-bpftrace-堆栈不显示函数名|显示unknown(How to print the function name instea
    link:Howtoprintthefunctionnameinsteadoftheaddressforustack#3108ajor:Symbolicationisbasedoffthesymboltableofthetargetapplication.Itdoesn'tlooklikeyou'redoinganythingwrongtome,butyoucoulddoublecheckthatsym......
  • [1081] The syntax and usage for the drop_duplicates and duplicated functions in
    Certainly!Here'sthesyntaxandusageforthedrop_duplicatesandduplicatedfunctionsinaGeoDataFrameinGeoPandas.drop_duplicatesFunctionThedrop_duplicatesmethodremovesduplicaterowsbasedononeormorecolumns.Syntax:GeoDataFrame.drop......
  • AI - RAG(Retrieval-Augmented Generation,检索增强生成)
    RAG(Retrieval-Augmented Generation,检索增强生成)技术是一种结合了检索和生成功能的自然语言处理(NLP)技术。它通过从大型外部数据库中检索与输入问题相关的信息,来辅助生成模型回答问题。以下是对RAG技术的详细解析:一、技术原理RAG技术的核心思想是将传统的检索技术与现代的自然语......
  • C++11 std::function与std::bind
    std::function与std::bind std::functionstd::function是一个可调用对象包装器,是一个类模板,可以容纳除了类成员函数指针之外的所有可调用对象,它可以用统一的方式处理函数、函数对象、函数指针,并允许保存和延迟它们的执行。例如//普通函数intadd(inta,intb){returna......
  • Task04 :Variables and Functions
    变量在Python中,变量是用来存储数据的。它不需要像C语言中需要对变量的类型进行定义,Python会根据赋值自动确认变量的类型。变量的命名规则:必须以字母或下划线开头。只能包含数字、字母、下划线。变量只是一个名称,用于与数据进行联系。定义变量时,现在内存空间中申请一块地......
  • C++中的std::function
    std::function()是C++标准库中的一个通用多态函数包装器,它可以存储,复制和调用任意可调用目标(函数,lambda表达式,绑定表达式或其他函数对象).std::function占用固定尺寸的内存.它允许我们将可调用对象(函数,函数指针,Lambda表达式等)包装成一个对象,使得我们可以像操作其他对......
  • 利用 Function 接口告别冗余(屎山)代码
    前言在Java开发的征途中,我们时常与重复代码不期而遇。这些重复代码不仅让项目显得笨重,更增加了维护成本。幸运的是,Java8带来了函数式编程的春风,以Function接口为代表的一系列新特性,为我们提供了破除这一难题的利剑。本文将以一个实际应用场景为例,即使用Java8的函数式编程......