js 把一个函数赋给一个变量时带括号与不带括号的区别

js 把一个函数赋给一个变量时带括号与不带括号的区别

function hi(){  
  var a = 1;  
  return function(){
   console.log(a++);
  };  
};         
var aaa = hi();
var bbb = hi;
aaa();
aaa();
bbb();
这段代码中 aaa与bbb的区别是什么?

aaa 是将 hi() 的运行结果赋值给它,即 return 返回的匿名函数,
此时有一个闭包,则每次调用 aaa 时都访问的同一个 a,
aaa() 第一次运行结果为 1,第二次为2
而 bbb 将是将 hi 这个函数名赋值给它,则调用 bbb() 后返回一个函数表达式,即function(){console.log(a++)};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你写一个函数来判断括号并计算表达式。以下是代码: ```c++ #include <iostream> #include <stack> #include <string> using namespace std; int calculate(string s) { stack<int> nums; stack<char> ops; int num = 0; char op = '+'; for (int i = 0; i < s.size(); i++) { char c = s[i]; if (isdigit(c)) { num = num * 10 + (c - '0'); } if ((!isdigit(c) && c != ' ') || i == s.size() - 1) { if (op == '+') { nums.push(num); } else if (op == '-') { nums.push(-num); } else if (op == '*') { int tmp = nums.top() * num; nums.pop(); nums.push(tmp); } else if (op == '/') { int tmp = nums.top() / num; nums.pop(); nums.push(tmp); } num = 0; op = c; } if (c == '(') { ops.push(op); op = '+'; nums.push(0); } if (c == ')') { while (ops.top() != '(') { char tmp_op = ops.top(); ops.pop(); int tmp_num = nums.top(); nums.pop(); if (tmp_op == '+') { nums.top() += tmp_num; } else if (tmp_op == '-') { nums.top() -= tmp_num; } else if (tmp_op == '*') { nums.top() *= tmp_num; } else if (tmp_op == '/') { nums.top() /= tmp_num; } } ops.pop(); } } while (!ops.empty()) { char tmp_op = ops.top(); ops.pop(); int tmp_num = nums.top(); nums.pop(); if (tmp_op == '+') { nums.top() += tmp_num; } else if (tmp_op == '-') { nums.top() -= tmp_num; } else if (tmp_op == '*') { nums.top() *= tmp_num; } else if (tmp_op == '/') { nums.top() /= tmp_num; } } return nums.top(); } int main() { string expr = "(1+2)*3+(4-2)*5"; cout << calculate(expr) << endl; return 0; } ``` 这个函数使用了两个栈,一个用来存储数字,一个用来存储操作符。在遍历表达式的过程中,如果遇到数字,就将其到 num 变量中,如果遇到操作符,就用当前的操作符计算之前的数字和操作符,并将结果压入数字栈中。如果遇到左括号,就将当前的操作符压入操作符栈,并将 num 变量清零。如果遇到右括号,就将操作符栈中的操作符依次取出,并用它们计算数字栈中的数字,直到遇到左括号为止。最后,将数字栈中剩余的数字相即可。 这个函数可以计算包含、减、乘、除和括号的表达式,并且可以正确处理优先级和括号
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值