DAY5、6 JS基础

 

代码目录:

js基础上:

  1. basicType.js
  2. definition.js
  3. function.js

js基础下:

  1. object.js
  2. class-this.js

//只有一种类型,浮点数
// console.log(1 == 1.0);

//单引号或双引号,没有单独的char类型
// console.log("hello world" == "hello world");

//typeof操作符
// console.log(typeof 1, typeof "", typeof false);

//访问一个没有被赋值的变量(属性),会返回undefined
// console.log(undefined, typeof undefined);
//这里本来应该存在一个对象,但是对象不存在;***null类型是object不是null
// console.log(null, typeof null);

// 字符串与别的类型相加会转换为字符串
// console.log(1 + "1", null + "is not undefined");

//+号可以将字符串转为数字
// console.log(+"1", +(1 + "1"), +"不是一个数字");

//不建议使用==会造成类型转换,使用===
// console.log(
//   1 == 1,
//   1 == "1",
//   1 == true,
//   0 == false,
//   "" == false,
//   null == undefined
// );

// console.log(1 === "1", 1 === true, 0 === false, null === undefined);

// falsy 值:javascript期望遇到一个布尔值(如判断或循环语句)
if (false || 0 || "" || undefined || null || NaN) {
  console.log("不应该走到这里");
} else {
  console.log("falsy 值");
}

//不建议使用var,统一使用let,const
// let是关键字,不是int那种类型关键字
let a = 1 + 2;
//可以修改,不限制类型
// a += 3;
// console.log(typeof a);
// a += "33";
// console.log(typeof a);
// let empty;
// //undefined
// console.log(empty);

const b = 1;
//不能修改const变量
// b = 2;//❌

// let num = 100;
// let str = ".";
// console.log("作用域1", num, str);
// //块级作用域,使用{}
// {
//   let str = "-";
//   console.log("作用域2", num, str);
//   {
//     let num = 200;
//     num += 10;
//     str += "-";
//     console.log("作用域3", num, str);
//   }
//   num++;
//   str += "-";
//   console.log("作用域2", num, str); //三个杠
// }
// console.log("作用域1", num, str);

// for函数内相对于一个作用域
// let num = 0;
// for (let i = 0; i < 3; ++i) {
//   for (let i = 0; i < 3; i++) {
//     num += i;
//   }
// }
// console.log(num);

const arr = ["index.html", "js", ["index.js"], "css", ["index.css"]];
let htmlStr = "";
let i = 0;
const len = arr.length;
while (i < len) {
  //当前项是文件夹
  if (i + 1 < len && typeof arr[i + 1] !== "string") {
    let subDirHtmlStr = "";
    const subArr = arr[i + 1];

    //与外层的i不影响
    for (let i = 0; i < subArr.length; ++i) {
      subDirHtmlStr = "<li>" + subArr[i] + "</li>";
    }
    subDirHtmlStr = "<ul>" + subDirHtmlStr + "</ul>";
    htmlStr += "<li>" + arr[i] + subDirHtmlStr + "</li>";
    i += 2;
  } else {
    htmlStr += "<li>" + arr[i] + "</li>";
    i += 1;
  }
}
htmlStr = "<ul>" + htmlStr + "</ul>";
document.body.innerHTML = htmlStr;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //函数的作用域还包括参数、
    function add(a, b) {
        return a + b;
    }
    // console.log(typeof add);
    // console.log(add(1, 2));

    function voidFunc(a, b) {
        console.log("voidFunc 参数", a, b);
    }
    // console.log(voidFunc(1, 2));
    // console.log(voidFunc(1));
    // console.log(voidFunc(1, 2, 3));

    function addWithDefault(a, b) {
        if (typeof b === "undefined") {
            b = 0;
        }
        if (typeof a === "undefined") {
            a = 0;
        }
        return a + b;
    }
    let a,
        b = undefined;
    // console.log(
    //   addWithDefault(),
    //   addWithDefault(10, a),
    //   addWithDefault(a, b),
    //   a,
    //   b
    // );

    //默认参数
    function addWithDefault1(a = 0, b = 0) {
        return a + b;
    }
    // console.log(addWithDefault1(), addWithDefault1(10));

    //函数提升,后面定义函数
    // console.log(minus(10, 2));
    function minus(a, b) {
        return a - b;
    }

    //console.log(minus1(10,2)) ;❌

    //函数表达式,可选的函数名字
    const minus1 = function minus2(a, b) {
        return a - b;
    };
    const minus3 = function (a, b) {
        return a - b;
    };
    //箭头函数
    const minus4 = (a, b) => {
        return a - b;
    };
    //函数体只有一个表达式,省略return和{}
    const minus5 = (a, b) => a - b;
    //参数一个省略小括号
    const returnSelf = (x) => x;

    //函数作为参数
    function binaryOperator(operand1, operand2, func) {
        const res = func(operand1, operand2);
        console.log(res);
        return res;
    }
    // binaryOperator(2, 5, "+");
    // binaryOperator(2, 5, "*");
    // binaryOperator(2, 5, add);
    // binaryOperator(2, 5, (a, b) => a * b);
    // binaryOperator(2, 5, (a, b) => a / b);

    //重复空格
    const repeatSpace = (num) => {
        let res = "";
        while (num--) {
            res += " ";
        }
        return res;
    };
    // console.log(repeatSpace(5) + "空格");

    //写一个生成函数的函数
    const buildRepeatChar = (char) => {
        return (num) => {
            let res = "";
            while (num--) {
                res += char;
            }
            return res;
        };
    };
    const repeatDot = buildRepeatChar(".");
    // console.log(repeatDot(5) + "点");
    // console.log(buildRepeatChar(" ")(5) + "空格");

    const buildRepeatCharWithLog = (char) => {
        let count = 0;
        return (num) => {
            count++;
            console.log("第" + count + "次调用,重复字符为" + char);
            let res = "";
            while (num--) {
                res += char;
            }
            return res;
        };
    };
    const char = "?";
    const count = 100;
    const repeatBar = buildRepeatCharWithLog("-");
    const repeatExclamatory = buildRepeatCharWithLog("!");
    // console.log(repeatBar(4));
    // console.log(repeatExclamatory(4));
    // repeatBar(4);
    // repeatBar(4);
    // repeatExclamatory(4);
    // repeatExclamatory(4);

    function buildClamp(lower, upper) {
        return (number) => {
            if (number < lower) {
                return lower;
            }
            if (number > upper) {
                return upper;
            }
            return number;
        };
    }

    function sumBy(list, iteratee) {
        let sum = 0;
        for (let i = 0; i < list.length; ++i) {
            sum += iteratee(list[i]);
        }
        return sum;
    }
    const func = buildClamp(0, 3);
    const question = sumBy([1, -2, 3, 9], func);
    // console.log(question);

    const arr = ["index.html", "CSS", ["index.css"], "JS", ["index.js"]];
    //递归实现返回数组代表的文件树HTML
    function toHTML(arr) {
        let res = "";
        let i = 0;
        const len = arr.length;
        while (i < len) {
            //当前项是文件夹
            if (i + 1 < len && typeof arr[i + 1] !== "string") {
                const subArr = arr[i + 1];
                res += "<li>" + arr[i] + toHTML(subArr) + "</li>";
                i += 2;
            }
            //是文件
            else {
                res += "<li>" + arr[i] + "</li>";
                i += 1;
            }
        }
        return "<ul>" + res + "</ul>";
    }
    // document.body.innerHTML = toHTML(arr);
    // document.body.innerHTML = toHTML(["root", arr]);
    // document.body.innerHTML = toHTML(["root", arr, "root", arr]);

</script>
</body>
</html>
//对象是一个属性(property)的集合
// 属性包含一个名(key or name)和一个值(value)

//对象字面值;key 需要字符串
let folder1 = {
  size: 2000,
  name: "floder1",
  subFiles: ["index.js"],
  "other object": null
};
// console.log(typeof folder1, folder1);

// 如果是合法的标识符,可以省略属性名单引号,所以
let folder2 = {
  size: 2000,
  name: "floder2",
  subFiles: ["index.js"],
  "other object": folder1 //非合法字符(不以数字开头,不含短杠、空格)
};

//访问对象属性使用.或者[]
// console.log(folder2.size, folder2.name);

// // []内可以用字符串表示非合法字符,可以填入任意有效值或表达式
// console.log(folder2["size"], folder2["name"], folder2["other object"]);

// let sizeKey = "size"; //值

// console.log(folder2[sizeKey], folder2["na" + "me"]); //表达式

//链式调用
// console.log(folder2["other object"].subFiles[0]);

//如果访问一个不存在的属性,返回undefined
// console.log(folder2.data, folder2["any" + "string"]);

//可以任意修改属性值
// folder2.size = folder2.size + 1000;
// folder2.name = null;
// folder2.subFiles = [];
// console.log(folder2);

//对象的属性是可变,可以增加更多属性
folder2.createTime = "2023-01-10";
folder2["modifiedTime"] = "2023-2-11";
// console.log(folder2);

//直接写对象字面值的时候,希望属性名是计算出来的,而不是固定的
const str = "variable";
const obj = {
  //属性名是variable
  [str]: "computed key",
  0.1: "number as key",
  log: () => {
    console.log("func as value");
  }
};
// console.log(obj.variable, obj[str]);

//obj.0.1 ❌
//数字会被转为字符串
// console.log(obj["0.1"], obj[0.1]);
// obj.log();

//一种更简要的写法
const year = 2020;
const mouth = 6;
// console.log({
//   //属性名是变量名,值是变量值
//   //不用写 year: year
//   year,
//   mouth,
//   print() {
//     console.log(year + "-" + mouth);
//   }
// });

const student = {
  name: "张三",
  age: "20",
  interests: ["跑步", "看书"],
  teacher: {
    name: "李四"
  }
};

//object是JS提供的一个全局对象
// console.log(Object.keys(student));

// for (const key in student) {
//   console.log(key, student[key]);
// }

//判断对象是否包含某一属性
// console.log(student.classmates === undefined);//❌,可能本身存在一个值为undefined
// Object.keys(student) 遍历数组判断
// 使用 in
// console.log("classmate" in student, "teacher" in student);

//属性删除
delete student.teacher;
// console.log("classmate" in student, "teacher" in student);

//对象的引用
const emptyObj1 = {};
const emptyObj2 = {};
// console.log(emptyObj1 !== emptyObj2);
const emptyObj3 = emptyObj1;
// console.log(emptyObj1 === emptyObj3);

emptyObj1.id = "emptyObj1.id";
// console.log(emptyObj1.id, emptyObj2.id, emptyObj3.id);

// const 标记了,引用是不变的,但对象的属性可变
// emptyObj1 = emptyObj2;❌

let emptyObj4 = emptyObj1;
// console.log(emptyObj4.id);
emptyObj4 = emptyObj2; //注意:这里是let
// console.log(emptyObj4.id);

//参数传入的是值;对于对象而言是,引用
function changeParam(basicValue, object) {
  // console.log("改变前", basicValue, object);
  basicValue = undefined;
  object = null;
  // console.log("改变后", basicValue, object);
}
changeParam(1, emptyObj1);
// console.log(emptyObj1);

function addProperty(object) {
  const key = "_private_key";
  object[key] = "from addProperty func";
}
addProperty(emptyObj2);
// console.log(emptyObj2);

const dataObj = {
  data: 1
};
function handel(obj) {
  //函数内dataObj不同于函数外dataObj
  const dataObj = {
    data: 1
  };
  obj.self = obj; //参数obj设置self属性指向自己本身
  dataObj.self = obj; //函数内的dataObj设置self指向参数obj
  return {
    //返回两个参数obj1,obj2分别指向obj,dataObj
    obj1: obj,
    obj2: dataObj
  };
}

const res = handel(dataObj); //obj指向外面的dataObj

console.log(
  res.obj1 === res.obj2, //obj1指向函数外参数dataObj,obj2指向函数内dataObj
  res.obj1.self === res.obj1, //self指向obj1本身即外面的dataObj
  res.obj2.self === res.obj2, //obj2.self指向obj即外面的dataObj,obj2指向内dataObj
  res.obj2.self.self === res.obj1 //obj2.self.self=obj.self=obj1
);

//深拷贝
function clone(parent) {
  const allParents = [];
  const allChildren = [];

  function _clone(parent) {
    const child = {};

    if (parent === null) {
      return null;
    }

    if (typeof parent !== "object") {
      return parent;
    }

    const index = allParents.indexOf(parent);

    if (index !== -1) {
      return allChildren[index];
    }
    allParents.push(parent);
    allChildren.push(child);

    for (const key in parent) {
      const value = parent[key];
      child[key] = _clone(value);
    }
    return child;
  }
}
console.log(clone(undefined), clone(null), clone(1), clone(" "));

class Rectangle {
  constructor(length, width) {
    //this 指向新的对象实例
    this.length = length;
    this.width = width;
  }

  area() {
    //this指向调用这个方法的实例
    return this.length * this.width;
  }
}

//利用class生成对象
const rect = new Rectangle(20, 10);
//等价于下面 对象字面值生成对象
// const rect1 ={
//   length:20,
//   width:10,
// }
// console.log(rect.area());

//类似对象字面值,可以动态改动属性
rect.length = 200;
// console.log(rect.area(), rect);

//方法area虽然可以访问,但不属于对象本身
// console.log(Object.keys(rect));
for (const x in rect) {
  // console.log(x, rect[x]);
}
//如果属性在类上,in返回true
// console.log("area" in rect);

//普通 Object
const rect2 = {
  length: rect.length,
  width: 30,
  area() {
    return this.length * this.width;
  }
};
// console.log(rect.area(), Object.keys(rect2), rect2, rect);

//普通类是Object
const obj1 = new Object();
obj1.id = 1;
const obj2 = {
  id: 1
};
// console.log(obj1, obj2);

//obj1,obj2都有Object共有的方法,比如说toString
// console.log(obj2.toString());

//数组的类是Array,数组也是对象
const arr1 = new Array(3);
arr1[0] = 10;
arr1[1] = 20;
arr1[2] = 30;
const arr2 = [10, 20, 30];

// //数组实用方法
// arr2.push(40);
// console.log(arr2);
// console.log(arr2.slice(1, 3));
// //indexOf获取数组元素的index
// console.log(arr2.indexOf(40), arr2.indexOf(1000));
// //join数组转字符串
// console.log(arr2.join(","));

//基本类型的包装对象
// const numObj = new Number(1);
// console.log(1, numObj, typeof numObj);
// const strObj = new String("");
// console.log(1, strObj, typeof strObj);
// const booleanObj = new Boolean(true);
// console.log(1, booleanObj, typeof booleanObj);

// //调用方法,不需要使用new Number/String/Boolean
// //使用基础类型时,js自动帮我们包装对应的对象,方便调用方法
// console.log("1234".length);
// console.log("1234".slice(1, 3));
// //字符串转数组
// console.log("1234".split("."));
// console.log("-^".repeat(10));

//数字后面不能直接加'.',js会认为是一个浮点数,要加一层()
//2.toFixed(3);❌
// console.log((2).toFixed(3));

//数组分类
// function groupBy(arr, iteratee) {
//   const object = {};
//   for (let i = 0; i < arr.length; ++i) {
//     const item = arr[i];
//     const key = iteratee(item);
//     if (object[key]) {
//       object[key].push(item);
//     } else {
//       object[key] = [item];
//     }
//   }
//   return object;
// }
// const res = groupBy([1, 100, 11, 5, 3, 15], (n) => n % 10);
// const question2 = Object.keys(res).length;
// console.log(question2, res);

function getCurrentTimeStr() {
  const date = new Date();
  const hour = date.getHours();
  const minutes = date.getMinutes();
  const second = date.getSeconds();
  //让冒号闪烁
  const separator = second % 2 ? " " : ":";
  return [hour, minutes, second].join(separator);
}

setInterval(() => {
  const str = getCurrentTimeStr();
  document.body.innerHTML =
    '<span style="font-size:30px;font-family:monospace;">' + str + " </span>";
}, 1000);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值