基本类型、引用类型

基本类型、引用类型

  • 基本类型值(数值、布尔值、字符串、null和undefined):指的是保存在栈内存中的简单数据段;
  • 引用类型值(对象、数组、函数、正则):指的是那些保存在堆内存中的对象,变量中保存的实际上只是一个指针,这个指针执行内存中的另一个位置,由该位置保存对象
    var a;
    var b;
    var obj;
    var obj2;


    a = 1;
    b = 2;

    var obj = {
        name: 'ruoyu',
        sex: 'male',
        age: 30,
        friend: {
            name: 'hello', 
            age: 100
        }
    }

    var newObj = {};



    b = a;
    console.log(b);

    var obj2 = obj;


    var obj3 = {name: 'hello'};
    var obj4 = {name: 'hello'};
    obj3 === obj4



    function sum(){
        console.log('sum...')
    }
    var sum2 = sum;
    sum2()

函数的参数传递

function inc(n){
    n++;
}
var a = 10;
inc(a);
console.log(a);

function incObj(obj){
    //var obj = o //0x0001
    obj.n++;
}

var o = {n: 10};  //o = 0x0001
incObj(o);
console.log(o);


function squireArr( arr ){
    //var arr = 0x0011
    for(var i = 0; i < arr.length; i++){
        arr[i] = arr[i] * arr[i];
    }
}
function squireArr2( arr ){
    var newArr = [];
    for(var i = 0; i < arr.length; i++){
        newArr[i] = arr[i] * arr[i];
    }
    return newArr;
}

var arr = [2,1,3,6]; //arr  0x0011
squireArr(arr);
console.log(arr); // [4,1,9,36]

var arr2 = squireArr2(arr)
console.log(arr2);

对象浅拷贝和深拷贝

//浅拷贝

    function shallowCopy(oldObj) {
        var newObj = {};
        for(var i in oldObj) {
            if(oldObj.hasOwnProperty(i)) {
                newObj[i] = oldObj[i];
            }
        }
        return newObj;
    }

//深拷贝

    function deepCopy(oldObj) {
        var newObj = {};
        for(var key in oldObj) {
            if(typeof oldObj[key] === 'object') {
                newObj[key] = deepCopy(oldObj[key]);
            }else{
                newObj[key] = oldObj[key];
            }
        }
        return newObj;
    }

results matching ""

    No results matching ""