前端入门笔记06 —— js基础

创建对象

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

输出如下

object {
  size: 2000,
  name: 'folder1',
  subFile: [ 'index.js' ],
  'other object': null
}
// 合法标识符可以省略冒号
let folder2 = {
    size : 2000,
    name : 'folder2',
    subFiles : ['index.js'],
    'other object' : folder1
};

console.log(folder2.name, folder2.subFiles);
console.log(folder2['name'], folder2['subFiles']);
let a = 'subFiles';
console.log(folder2['na'+'me'], folder2[a]);
//三个输出等价 folder2 [ 'index.js' ]


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

若访问一个未定义对象,返回undefined

访问修改

可以随意修改

folder2.size = folder2.size + 100;

对象属性可变且可以增加新属性

folder2.NEWOBJECT = 'no';
folder2["new object"] = "yes"
console.log(folder2);

输出

{
  size: 2100,
  name: 'folder2',
  subFiles: [ 'index.js' ],     
  'other object': {
    size: 2000,
    name: 'folder2',
    subFile: [ 'index.js' ],    
    'other object': null        
  },
  NEWOBJECT: 'no',
  'new object': 'yes'
}

动态增删

有时候我们希望 属性的名字是计算出来的。而不是固定的

let str = 'vairable';
const obj = {
    [str] : "an object",
    0.1 : 'number', //强制给你转字符串
    log : () =>{console.log("function in obj")}
};
console.log(obj);
//{ vairable: 'an object', '0.1': 'number', log: [Function: log] }
console.log(obj[0.1]);//自动帮你转换
obj.log();

如果属性名的value就是变量本身,可以省略:和后面的部分

let year = 2000;
let month = 1;
let day = 1;
const obj = {
    year,
    month,
    day,
    print(){
        console.log('hello world');
    }
};
console.log(obj);
//{ year: 2000, month: 1, day: 1, print: [Function: print] }   

遍历对象属性

console.log(Object.keys(obj));
//[ 'year', 'month', 'day', 'print' ]


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

判断对象是否包含属性的话最后不用 === undefined,因为有可能属性本身定义了且就是undefined

使用 遍历数组或者in

console.log('centery' in obj, 'year' in obj);
//false true

删除 delete

delete obj.day;
console.log(obj);
//{ year: 2000, month: 1, print: [Function: print] }

对象引用

const obj1 = {};
const obj2 = {};
const obj3 = obj1;

console.log(obj1 === obj2);
console.log(obj1 === obj3);
//false true

obj1.id = 'id';
console.log(obj1.id, obj2.id, obj3.id)
//id undefined id

需要注意,const标记引用的对象不变,但是对象内的属性可以变化

let obj4 = obj1;
console.log(obj4.id);
let obj4 = obj2;
console.log(obj4.id);
//id undefined

使用函数的时候,参数传入,对于变量来说是形式变量(只传值不改),对于对象是引用

function change(val, obj)
{
    console.log(val,obj);
    val = undefined;
    obj = null;
    console.log(val,obj);
}
let b = 1;
change(b, obj1);
console.log(b, obj1);

//1 { id: 'id' }
//undefined null
//1 { id: 'id' }

function change2(val, obj)
{
    console.log(val,obj);
    val = undefined;
    obj.id = null;//这里不一样 
    console.log(val,obj);
}
change2(b, obj1);
console.log(b, obj1);
//1 { id: 'id' }
// undefined { id: null }
//1 { id: null }

深拷贝

function deep_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;
    }
    return _clone(parent);
}

class & this

class rectangle{

    constructor(length, width)
    {
        this.length = length;
        this.width = width;
    }
    area()
    {
        return this.length * this.width;
    }
}
const rec = new rectangle(20, 10);
//对象内容可以改
rec.length = 200;

//方法可以访问,但不属于对象本身
console.log(Object.keys(rec));
//没有area

//但是属性在类上还是返回true
console.log('area' in rec);
//ture

内置对象

  1. Object
  2. Array
  3. Number
  4. String
  5. Boolean
  6. 其他
//普通object对比class
const rec1 = {
    length : rec.length,
    width : 20,
    area()
    {
        return this.length * this.width;
    }
}
console.log(rec1.area(), Object.keys(rec1), rec1, rec)
//4000 [ 'length', 'width', 'area' ] { length: 200, width: 20, area: [Function: area] } rectangle { length: 200, width: 10 } 

普通的类为Object

const obj4 = new Object();
obj4.id = 1;
const obj5 = {id : 1};
console.log(obj4, obj5);
console.log(obj5.toString());
//obj5为object

数组也是对象

const arr = Array(3);
arr[0] = arr[1] = arr[2] = 2;
const arr2 = [1,2,3];

//插入
arr2.push(4);

//切片
console.log(arr1.slice(1,3));
//获取index
console.logg(arr.indexOf(1)), arr.indexOf(100);
//0 和 -1

//变字符串
console.log(arr1.join('.'));


array和object是类也是对象

console.log(Object.keys({a:1}));
console.log(Array.isArray(100));

其他基本类型
用的时候不用声明new,系统会帮忙包装

const num = new Number(0);
console.log(1, num, typeof num);
const str = new String('');
console.log('', str, typeof str);
const bool = new Boolean(0);
console.log(false, bool, typeof bool);
//1 [Number: 0] object
// [String: ''] object
//fasle [Boolean: false] object  

需要注意数字后面无法直接加.因为系统会认为这是个浮点数,要先加个括号再加点

console.log((2).toFixed(3));

简易数字时钟

function getCurrentTime()
{
    const date = new Date();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    const separator = second % 2 ? " " : ":";

    return[hour, minute, second].join(separator);
}
setInterval(() => {
    const str = getCurrentTime();
    document.body.innerHTML = 
    '' + str + ""
},
     1000);

你可能感兴趣的:(前端,javascript,前端,开发语言)