Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js面试题 #16

Open
rainit2006 opened this issue Feb 26, 2018 · 1 comment
Open

js面试题 #16

rainit2006 opened this issue Feb 26, 2018 · 1 comment

Comments

@rainit2006
Copy link
Owner

No description provided.

@rainit2006
Copy link
Owner Author

rainit2006 commented Feb 26, 2018

dwqs/blog#17

■对于 return 、break、continue 等语句,如果后面紧跟换行,解析器一定会自动在后面填充分号(;)

function foo2()
{
  return
  {
      bar: "hello"
  };
}

等同于

function foo2()
{
  return;
  {
      bar: "hello"
  };
}

所以该函数返回 undefined。

■ NaN
NaN 是 Not a Number 的缩写,JavaScript 的一种特殊数值,其类型是 Number,可以通过 isNaN(param) 来判断一个值是否是 NaN。

console.log(isNaN(23)); //false
console.log(isNaN('ds')); //true

ES6 中,isNaN() 成为了 Number 的静态方法:Number.isNaN().

■ 浮点型处理
JavaScript 中的浮点数采用IEEE-754 格式的规定,这是一种二进制表示法,可以精确地表示分数,比如1/2,1/8,1/1024,每个浮点数占64位。但是,二进制浮点数表示法并不能精确的表示类似0.1这样 的简单的数字,会有舍入误差。
对于保证浮点数计算的正确性,有两种常见方式。
一是先升幂再降幂.

function add(num1, num2){
  let r1, r2, m;
  r1 = (''+num1).split('.')[1].length;
  r2 = (''+num2).split('.')[1].length;

  m = Math.pow(10,Math.max(r1,r2));
  return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2));   //0.3
console.log(add(0.15,0.2256)); //0.3756

二是是使用内置的 toPrecision() 和 toFixed() 方法,注意,方法的返回值字符串。

function add(x, y) {
    return x.toPrecision() + y.toPrecision()
}
console.log(add(0.1,0.2));  //"0.10.2"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant