Skip to content

来自知乎用户:mcZone 的回答 #1

@songStar0904

Description

@songStar0904

知乎用户:@mcZone
向下取整:

var a = ~~1.2; // 1
var a = 3.4>>0; // 3

但是两者最好只用在正整数上, 因为只是射雕小鼠部分。 Math.floor(-1.2) 应该为-2, 这两种方法为-1/

转数字:

var time = + new Date();

设默认值:

function foo(bar) {
  var foobar = bar || 'default';
  // bar 为 undefined, null, ‘’, 0, false, NAN 都得到 default。 所以使用es6 可以解决这个问题。
}
function foo(bar = 'default') {
  var foobar = bar;
}
// 坑
[] || 'aa'; // []
{} || 'aa'; // Unexpected token ||
({}) || 'aa'; // {}

NAN 的坑:

// NaN - 不是一个数字
isNaN('a'); // true
isNaN(null); // false null先被隐式转换为0, 是一个数字

数组传递和赋值:

var a = [1, 2, 3];
var b = a;
delete b[1];
console.log(a); // [1, undefined, 3] a, b 指向同一个地址, b改变导致地址上的数组也改变, a也改变。 对象也是一样的。

var a = [4, 5, 6];
var b = a.slice(0);
delete b[1];
console.log(a); // [4, 5, 6]
console.log(b); //[4, undefined, 6]

对象与Function:

console.log(typeof Function); // 'function'
console.log(typeof Object); // 'function'

函数声明:

aa();
function aa(){return true;} // true 声明提前

bb();
var bb = function(){return true;} // TypeError

toString():

2.toString(); // SyntaxError
2 .toString(); // '2'
2..toString(); // '2'
(2).toString(); // '2'
[1,[2,"abc","",0,null,undefined,false,NaN],3].toString();
//"1,2,abc,,0,,,false,NaN,3"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions