js

作者: jh2k15 | 来源:发表于2018-01-20 16:54 被阅读0次

1

var obj = {};

console.log((obj !== null) & (typeof obj === "object") && (toString.call(obj) !== "[object Array]"));

console.log(Object.prototype.toString.call(obj) === "[object Object]");

//用 typeof 判断一个对象变量,null 的结果也是 object,Array 也是 object,有时候我们需要的是 “纯粹” 的 object 对象

2

(function(){
  var a = b = 3;
})();

console.log("a defined? " + (typeof a !== 'undefined'));   //a defined? false
console.log("b defined? " + (typeof b !== 'undefined'));   //b defined? true
(function(){
  b = 3;
  var a = b;
})();
//IIFE 中的赋值过程是从右到左,a 是局部变量,b 是全局变量。

3

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};

4

function foo1()
{
  return {
      bar: "hello"
  };
}
//{bar: "hello"}
function foo2()
{
  return
  {
      bar: "hello"
  };
}
//undefined
//第二个函数会返回 undefined。这是由于 Javascript 的封号插入机制决定的,如果某行代码,return 关键词后没有任何东西了,将会自动插入一个封号,显然 foo2 函数中,当 return 后被插入一个封号后,尽管后面的语句不符合规定,但是因为没有执行到,所以也不会报错了。没有 return 任何东西的函数,默认返回 undefined。
所以很多 Javascript 规范建议把 { 写在一行中,而不是另起一行。
function foo2()
{
  return;
  {
      bar: "hello";
  };
};

5

console.log('abc' / 4);   //NaN
console.log(4 * 'a');  //NaN

console.log(typeof (4 * 'a')); // number

console.log(NaN === NaN); // false
//判断一个变量是不是 NaN 可以用 isNaN() 函数,但是这 并不是一个完美的函数,有些时候用 value !== value 似乎更准确,幸运的是,ES6 已经有 Number.isNaN() 方法,将比 isNaN() 准确的多
console.log(0.1 + 0.2);   //0.30000000000000004
console.log(0.1 + 0.2 == 0.3);  //false
var a = -1.2223;

 console.log(a ^ 0);  // -1
 console.log(a | 0);  // -1
 console.log(a > 0); // false

 console.log(Math.round(a)); // -1
 console.log(Math.floor(a)); // -2
 console.log(Math.ceil(a));  // -1
(function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 1000); 
    setTimeout(function(){console.log(3)}, 0); 
    console.log(4);
})();

//1
//4
//3
//2
//Javascript 是单线程的语言, 一些异步事件是在主体 js 执行完之后执行即可

求和

function sum(x) {
  if (arguments.length == 2) {
    return arguments[0] + arguments[1];
  } else {
    return function(y) { return x + y; };
  }
}
function sum(x, y) {
  if (y !== undefined) {
    return x + y;
  } else {
    return function(y) { return x + y; };
  }
}

console.log(sum(2,3));   //5
console.log(sum(2)(3));  //5

https://mp.weixin.qq.com/s/ovg2_dB6IhAWEf0JBjcGfg

相关文章

网友评论

      本文标题:js

      本文链接:https://www.haomeiwen.com/subject/kvptaxtx.html