Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

weird array behaviour in javascript

I know arrays in javascript are a bit special, compared to other languages, but I don't really get this behaviour, or what's going on here.

I'd like to know why it happens and why I don't get an empty array:

function setupWindowProgBar(settings, window, palette, arr){
    console.log('start');
    console.log(arr);
    if(typeof arr == 'undefined'){
        var arr = [];
    }
    console.log(arr);
    console.log('stop');
    var arrLen = arr.length;
    arr[arr.length] = createProgBar('master', 'bg', window, 0, settings.fillColor, settings.strokeColor, settings.textColor, palette, 'percent', settings.reqType, settings.sourceType, settings.sourceTarget, settings.sourceId);
    return arr;
}

produces this in the console:

start
undefined
[]
    0:
    barType:"master"
    bgcolor:"#12181f"
    curVal:160
        data:
        all_goals:160
        cost_hours:160
        cost_hours_spent:0
        cost_money:31610
        cost_money_owned:0
        parentObj:"progBar"
        progress_goals:5
        recurring:"no"
        wanted_timer:"2018-03-26 05:19:33"
        __proto__:Object
    fill:"#255f6f"
    height:59
    maxVal:5
    maxWidth:168
    sectionHeight:59
    stroke:"#7b9dac"
    text:"3%"
    textColor:"#dee5ed"
    textOpt:"percent"
    width:200
    x:33
    y:81
__proto__:Object
height:100
text:"omanko"
length:1
__proto__:Array(0)
stop

I do reckognize the objects in here, but it's not from global pollution as far as I can tell - console.log(window.arr) says that there are no global variables named arr, and I haven't modified the prototype.

Surely, that shouldn't effect a new array declaration anyway?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This behaviour isn't limited to arrays, any object behaves this way in the console

What you are seeing is the result of console in all browsers "lying" to you

if you console.log(anyobject) and inspect that object in the console, what you will see is current anyobject - not what it was when console.log was executed

var obj = {}
console.log(obj);
obj.test = 1;

var arr = [1];
console.log(arr);
arr.push(2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...