javascript 一些零碎知识点

No 1 包装对象问题

属性

str.t = 4; // 试着添加一个属性
// 4
str.t; // 发现无法访问了
// undefined

当把一个基本数据类型尝试使用对象的方法的时候,js会尝试的将其转换为相应的基础类型包装对象(var str = new String('str');),当该次访问结束之后,这个临时的包装对象就会立即销毁,所以再次访问的时候,就是undefined。通其类似的还有Boolean、Number

No 2 数据类型的判断

  • typeof

适合判断基本数据类型和function的判断

 "string"
typeof 123 ===> "Number"
typeof [1,2,3] ===> "object"
typeof new Date() ===> "object"
typeof function(){alert('111');}  ===> "function"
typeof undefined ===> "undefined"
typeof NaN ===> "number"
typeof null ===> "object"
  • instanceof

判断已知的对象类型或者是自定义的对象,遇到不同iframe和window间检测时失效

目标对象 + instanceof + 函数构造器

原理: 判断左边的对象的原型链上是否有右侧的构造函数的prototype属性

// 定义一个构造函数
function Person(){

}
// 定义一个构造函数
function Student(){

}
// 每一个构造函数都有一个prototype对象属性, 这个对象属性将会作为通过new Person()创建的对象的一个原型。
// 也就是当我们在new 一个对象的时候,这个对象的原型就指向了这个构造函数的prototype。

Student.prototype = new Person(); // student继承至person

var bson = new Student();
bson instanceof Student
// false

bson instanceof Person
// true

  • Object.prototype.toString.apply()

判断基本数据类型和内置对象

Object.prototype.toString.apply(new Function); // "[object Function]"
Object.prototype.toString.apply(new Object); // "[object Object]"
Object.prototype.toString.apply(new Date); // "[object Date]"
Object.prototype.toString.apply(new Array); // "[object Array]"
Object.prototype.toString.apply(new RegExp); // "[object RegExp]"
Object.prototype.toString.apply(new ArrayBuffer); // "[object ArrayBuffer]"
Object.prototype.toString.apply(Math); // "[object Math]"
Object.prototype.toString.apply(JSON); // "[object JSON]"
var promise = new Promise(function(resolve,reject) {
resolve();
});
Object.prototype.toString.apply(promise); // "[object Promise]"
Object.prototype.toString.apply(124)
// "[object Number]"
Object.prototype.toString.apply("222")
// "[object String]"
Object.prototype.toString.apply(true)
// "[object Boolean]"
Object.prototype.toString.apply(null)
// "[object Null]"
Object.prototype.toString.apply(null) === "[object Null]" // 在IE6/7/8下存在有兼容性问题

No 3 特殊运算符

  • ,逗号运算符
var a = (1,4);
a; // 4
  • in
window.x = 10;

x in window; // true

  • delete

删除对象的一个属性

delete window.x;
  • void
void() // undefined
void(0) // undefined

No 3 js中固定精度(小数位的舍的问题)toFixed()方法

var a = 3;
var b = 1.1;
var z = a*b;
console.log(z); // 3.3000000000000003
console.log(z.toFixed(2)); // 3.30

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...