关于javascript:运算符小括号

9次阅读

共计 681 个字符,预计需要花费 2 分钟才能阅读完成。

1、分组操作

  • 扭转运算符的优先级
const aa = 100 * (200 + 300);

console.log(aa);
  • 括号外面必须有值
console.log(());

function Test(){}();
// 等价于上面的代码,之所以报错是因为括号里没有值
// function Test()
// ()

function Test(){}(1); // 此时就不会报错了

2、函数参数

  • 函数定义和调用时,参数都要放在小括号中
function Test(a,b,c){console.log(a,b,c);
}

Test(1,2,3)

3、函数调用

  • 函数调用只能是函数表达式
const test2 = function(){console.log('Function Expression');
}

test();
  • 函数申明不可能被调用
function Test(){}();
// 等价于上面的代码,之所以报错是因为括号里没有值
// function Test()
// ()

function Test(){}(1); // 此时就不会报错了

4、小括号内只能是表达式

  • 当解析器遇到 function 关键字时,默认是函数申明,()能把函数申明转为函数表达式
(function test(){console.log('Function Declaration');
})()
  • 把解析器遇到 {} 时,默认认为是代码块,()把代码块转为表达式
const obj = {
  name: 'wwt',
  age: '18'
}

const strObj = JSON.stringify(obj);
const res = eval('('+ strObj + ')');

console.log(res);
正文完
 0