美文网首页
JS实用小窍门

JS实用小窍门

作者: MrAlexLee | 来源:发表于2018-06-28 17:22 被阅读6次
1,删除数组尾部元素

改变数组的length值就可以删除

const arr = [0,1,2,3,4,5];
arr.length = 3;
console.log(arr);  //=>[0,1,2]
arr.length  = 0;
console.log(arr); //=>[]
console.log(arr[2]);//=>undefined
2,数组解构
const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
console.log(typeof csvFileLine); //=> string
//split方法会将字符串变成object,但是不会影响原值
console.log(csvFileLine.split(','));//=>["1997", "John Doe", "US", "john@doe.com", "New York"]
const { 2: country, 4: state } = csvFileLine.split(',');
console.log(country);//=>'US'
console.log(state);//=>'New York'

这里介绍一下typeof 各种数据类型

  console.log(typeof 2); //=>number
  console.log(typeof 'abc');//=>string
  console.log(typeof true);//=>boolean
  console.log(typeof null);//=>object
  console.log(typeof undefined);//=>undefined
  console.log(typeof {});//=>object
  console.log(typeof []);//=>object
  console.log(typeof (function () {}));//=>function
那么怎么区别{},[],null的类型呢?

1,使用jQuery
2,使用原生原型扩展函数

jquery方法

直接使用jQuery.type,另外还可以判断日期date和正则regexp

使用原生扩展函数
let getType=Object.prototype.toString
    getType.call('aaaa')  //=> [object String]
    getType.call(2222) //=> [object Number]
    getType.call(true)//=> [object Boolean]
    getType.call(undefined)//=> [object Undefined]
    getType.call(null)//=> [object Null]
    getType.call({})//=> [object Object]
    getType.call([])//=> [object Array]
    getType.call(function(){})//=> [object Function]

另外在判断空对象和空数组的时候不能直接判断,因为空数组和空对象都是true

如何判断对象为空

可以使用ES6

let data = {};
let arr = Object.keys(data);
console.log(arr.length==0);//=>true

可以使用jQuery

let data = {};
let arr = jQuery.isEmptyObject(data);
console.log(arr);//=>true

for in 判断

var obj = {};
var b = function() {
for(var key in obj) {
return false;
}
return true;
}
alert(b());//true

将json对象转化为json字符串,再判断该字符串是否为"{}"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);//true
如何判断数组为空
var a = []
if(Object.prototype.toString.call(a) === '[object Array]' && a.length === 0){
    console.log(true)
}

相关文章

网友评论

      本文标题:JS实用小窍门

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