JS基础

2021-11-23  本文已影响0人  走停2015_iOS开发
function User() {}
User.prototype = {
  lessons: ["JS", "VUE"]
};
const lisi = new User();
const wangwu = new User();

lisi.lessons.push("CSS");

console.log(lisi.lessons); //["JS", "VUE", "CSS"]
console.log(wangwu.lessons); //["JS", "VUE", "CSS"]
undefined:未赋值与未定义的变量值都为 undefined
null: 用于定义一个空对象,即如果变量要用来保存引用类型,
可以在初始化时将其设置为null
continue hdcms: 跳出n的循环
break houdunren:  跳出I的循环
houdunren: for (let i = 1; i <= 10; i++) {
  hdcms: for (let n = 1; n <= 10; n++) {
    if (n % 2 != 0) {
      continue hdcms;
    }
    console.log(i, n);
    if (i + n > 15) {
      break houdunren;
    }
  }
}
let a = 1;
console.log(typeof a); //number

let b = "1";
console.log(typeof b); //string

//未赋值或不存在的变量返回undefined
var hd;
console.log(typeof hd);

function run() {}
console.log(typeof run); //function

let c = [1, 2, 3];
console.log(typeof c); //object

let d = { name: "houdunren.com" };
console.log(typeof d); //object
let hd = [];
let houdunren = {};
console.log(hd instanceof Array); //true
console.log(houdunren instanceof Array); //false

let c = [1, 2, 3];
console.log(c instanceof Array); //true

let d = { name: "houdunren.com" };
console.log(d instanceof Object); //true

function User() {}
let hd = new User();
console.log(hd instanceof User); //true
console.log(Number("houdunren")); //NaN
console.log(2 / 'houdunren'); //NaN
有new没有new的区别
let now = new Date();
console.log(now);
console.log(typeof date); //object
console.log(now * 1); //获取时间戳

//直接使用函数获取当前时间
console.log(Date());
console.log(typeof Date()); //string

//获取当前时间戳单位毫秒
console.log(Date.now());
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
1. user = [];
2. user.length = 0;
3. user.splice(0, user.length);
4.while (user.pop()) {} 使用pop/shift删除所有元素,来清空数组
let array = ["hdcms", "houdunren"];
let hd = [1, 2];
let cms = [3, 4];
console.log(array.concat(hd, cms)); //["hdcms", "houdunren", 1, 2, 3, 4]
---------------------------------------------------------------
console.log([...array, ...hd, ...cms]);
---------------------------------------------------------------
array.copyWithin(target, start, end)
1.indexOf 查找字符串将找不到,因为indexOf 类似于===是严格类型约束。
let arr = [7, 3, 2, '8', 2, 6];
console.log(arr.indexOf(8)); // -1

2.lastIndexOf

3.使用 includes 查找字符串返回值是布尔类型更方便判断 使用includes等不能查找引用类型,因为它们的内存地址是不相等的

4.find 方法找到后会把值返回出来
let arr = ["hdcms", "houdunren", "hdcms"];
let find = arr.find(function(item) {
  return item == "hdcms";
});
console.log(find); //hdcms

5.findIndex 返回下标
let arr = [7, 3, 2, '8', 2, 6];
console.log(arr.findIndex(function (v) {
    return v == 8;
})); //3
    let user1 = {
      name: '李四',
      key: Symbol()
    }
    let user2 = {
      name: '李四',
      key: Symbol()
    }
    let grade = {
      [user1.key]: { js: 100, css: 90 },
      [user2.key]: { js: 900, css: 90 },
    };
    console.table(grade);
    console.table(grade[user1.key]);
image.png
https://doc.houdunren.com/js/5%20Symbol.html#缓存操作
下例中的数组被 arr 引用了,引用计数器+1
数据又添加到了 hd 的WeaSet中,引用计数还是1
当 arr 设置为null时,引用计数-1 此时对象引用为0
当垃圾回收时对象被删除,这时WakeSet也就没有记录了
var hd = '后盾人';
function get() {
  "use strict"
  return this.hd;
}
console.log(get());
//严格模式将产生错误 Cannot read property 'name' of undefined
let obj = {
  site: "后盾人",
  show() {
    console.log(this.site); //后盾人
    console.log(`this in show method: ${this}`); //this in show method: [object Object]
    function hd() {
      console.log(typeof this.site); //undefined
      console.log(`this in hd function: ${this}`); //this in hd function: [object Window]
    }
    hd();
  }
};
obj.show();
let Lesson = {
  site: "后盾人",
  lists: ["js", "css", "mysql"],
  show() {
    return this.lists.map(function(title) {
      return `${this.site}-${title}`;
    }, this);
  }
};
console.log(Lesson.show());//['后盾人-js', '后盾人-css', '后盾人-mysql']
let Lesson = {
    site: "后盾人",
    lists: ["js", "css", "mysql"],
    show() {
      const self = this;
      return this.lists.map(function(title) {
        return `${self.site}-${title}`;
      });
    }
  };
  console.log(Lesson.show());
    // call是一个方法 函数的方法
    Function.prototype.newCall = function (context) {
     //1. 找到未来this的指向,即arguments[0], 如果没有传入任何参数 那么我们将this指向window
     //如果传入的类型是string number boolean 我们要对其进行包装
     var target = Object(arguments[0])||window
     //2.找到未来要执行的函数 并且改变其this的指向 相当于把this这个未来要执行的函数放在target对象里面 让函数成为对象的一部分
     target.fn = this;
     //4.把arguments[0]以外的参数 传入函数 并且执行该函数
     var params = [];
     for(var i = 1; i< arguments.length; i++){
       params.push(arguments[I]);
     } 
     //var result = target.fn (...params)
     var result = eval('target.fn('+params.toString()+')');
     //5.删除目标对象的函数
     delete target.fn
     return result
    };
    let obj = {
      name: "Jowie",
    };
    function addAge(age,test) {
      this.age = age;
      console.log(this);
      return this;
    }
    addAge.newCall(obj,20,30)
Function.prototype.myApply =function(context,arr){
context = Object(context) || window;
context.fn = this;
var result;
if(!arr){
    result= context.fn();
}else{
    var args = [];
    for(var i=0;i<arr.length;i++){
        args.push('arr['+i+']');
    }
    result = eval('context.fn('+args.toString()+')')
}
delete context.fn;
return result;
}

var q = {name:'chuchu'};
var arg1 = 1;
var arg2= [123]
function eat(n,m){
    console.log(this,n,m);
}
eat.myApply(q,[arg1,arg2])
//bind方法,是改变当前调用bind方法的函数this指向,但是不会立即执行当前函数,而是返回一个新的函数。并且支持给新的函数传入参数执行,从而出发之前调用bind方法的函数执行,并且参数透传进去。bind方法是高阶函数的一种
Function.prototype.myBind = function(){
var context = arguments[0];
var self = this;
return function (){
    self.myApply(context,arguments)
}
};
var j = {name:1};
var k = [123]
function drink (k){
    console.log(this.name,k);
}
var fn = drink.myBind(j);
fn(k);
let obj = {name: "后盾人"};
let hd = {
  web: "houdunren.com"
};
//设置hd为obj的新原型
Object.setPrototypeOf(obj, hd);
console.log(obj);
console.log("web" in obj); //true
console.log(obj.hasOwnProperty("web")); //false
const hd = {
  name: "后盾人",
  age: 10
};
console.log(Object.keys(hd)); //["name", "age"]
console.log(Object.values(hd)); //["后盾人", 10]
console.table(Object.entries(hd)); //[["name","后盾人"],["age",10]]
Object.getOwnPropertyNames(hd)//["name", "age"]
let user = {
    name: '后盾人'
};
let hd = {
    stu: Object.assign({}, user)
};
hd.stu.name = 'hdcms';
console.log(user.name);//后盾人
1. 浅拷贝仅仅是指向被拷贝的内存地址,如果原地址中对象被改变了,那么浅拷贝出来的对象也会相应改变。()
2. 我在想如何让obj1复制obj的对象内容,在我对obj1进行修改时,不影响obj。通过递归调用浅拷贝来解决。
//深拷贝 实现
        function deepCopy(obj){
            let temp = obj.constructor === Array?[]:{};
            for(let val in obj){
                temp[val] = typeof obj[val] == 'object' ? deepCopy(obj[val]) : obj[val];
            }
            return temp;
        }
        console.log(deepCopy(obj));
使用 Object.getOwnPropertyDescriptor查看对象属性的描述
使用Object.defineProperty 方法修改属性特性
Object.preventExtensions 禁止向对象添加属性
Object.isExtensible 判断是否能向对象中添加属性
Object.seal()方法封闭一个对象,阻止添加新属性并将所有现有属性标记为 configurable: false
Object.freeze 冻结对象后不允许添加、删除、修改属性,writable、configurable都标记为false

https://doc.houdunren.com/js/10%20对象.html#属性特征

let hd = {
    "title": "后盾人",
    "url": "houdunren.com",
    "teacher": {
        "name": "向军大叔",
    },
    "toJSON": function () {
        return {
            "title": this.url,
            "name": this.teacher.name
        };
    }
}
console.log(JSON.stringify(hd)); //{"title":"houdunren.com","name":"向军大叔"}
const Tool = {
  max(key) {
    return this.data.sort((a, b) => b[key] - a[key])[0];
  }
};
class Lesson {
  constructor(lessons) {
    this.lessons = lessons;
  }
  get data() {
    return this.lessons;
  }
}
Object.assign(Lesson.prototype, Tool);
const data = [
  { name: "js", price: 100 },
  { name: "mysql", price: 212 },
  { name: "vue.js", price: 98 }
];
let hd = new Lesson(data);
console.log(hd.max("price"));
上一篇 下一篇

猜你喜欢

热点阅读