JavaScript 冷知识

87的海雷 / 2023-08-30 / 原文

数据类型的判断

typeof  Symbol();  // symbol 有效
typeof  '';  // string 有效
typeof  1;  // number 有效
typeof  true;  //boolean 有效
typeof  undefined;  //undefined 有效
typeof  new  Function();  // function 有效
typeof  null;  //object 无效
typeof  []  ;  //object 无效
typeof  new  Date();  //object 无效
typeof  new  RegExp();  //object 无效
[]  instanceof  Array;  //true
{}  instanceof  Object;//true
new  Date()  instanceof  Date;//true
new  RegExp()  instanceof  RegExp//true
null  instanceof  Null//报错
undefined  instanceof  undefined//报错
Object.prototype.toString.call('')  ;  // [object String]
Object.prototype.toString.call(1)  ;  // [object Number]
Object.prototype.toString.call(true)  ;  // [object Boolean]
Object.prototype.toString.call(undefined)  ;  // [object Undefined]
Object.prototype.toString.call(null)  ;  // [object Null]
Object.prototype.toString.call(new  Function())  ;  // [object Function]
Object.prototype.toString.call(new  Date())  ;  // [object Date]
Object.prototype.toString.call([])  ;  // [object Array]
Object.prototype.toString.call(new  RegExp())  ;  // [object RegExp]
Object.prototype.toString.call(new  Error())  ;  // [object Error]

 

深拷贝

var a ={ a:1,b:2 }
var b = JSON.parse(JSON.stringify(a))

 

继承

var Person = function() {  age:18,name:""}
var Student = function() {}
//创建继承关系,父类实例作为子类原型
Student.prototype = new Person()
var s1 = new Student();

判断数组

let arr=[1,3,5,7,8,10,2,5,6]
 let Array= arr.every((v,i)=>{
     return v>=1
   })
   console.log(Array); //true

 let arr=[1,3,5,7,8,10,2,5,6]
 let Array= arr.every((v,i)=>{
     return v>5
   })
   console.log(Array); //false
let Array= arr.some((v,i)=>{
     return v>9
   })
   console.log(Array); //true

循环

for 循环

for (let k = 0; k < 10; k++) {
  console.time(k);
}

while 和 do-while 循环


  let i = 0;
  while (i < len) {
    i++;
  }
  let i = 0;
  do {
    i++;
  } while (i < len);

 

forEach、map、reduce 循环

[1, 2, 3, 4, 5].forEach(x=> console.log(x))
[1, 2, 3, 4, 5].map(x=> console.log(x))
[1, 2, 3, 4, 5].reduce((a,b)=> a + b)

 

for-of 循环

for (const value of fruits) {
  console.log(value); 
}

 

for-in 循环;

for (let key in arr) { console.log(key) }