简体   繁体   中英

strange js array behavior

Here is sample code:

console.log('params is empty: '+(params == ''));
console.log('params: '+params);
console.log('df: '+params['df']);
$.each(params, function(p_name, p_val){
    console.log(p_name+': '+p_val);
});

And responce:

params is empty: true
params:
df: 15.03.2012

How this can be?

Presumably (it has to be that way as you are showing use a predefined variable so we can't know what is actually in it except by drawing conclusions from the tests you are performing on it) because params is an array and not an object .

Arrays are designed to hold an ordered sequence of values with numeric keys.

Objects have values with (relatively) arbitrary keys.

Stringifying an array only joins the numeric keys. So comparing it to an empty string will only give a false value if there are numeric keys.

$.each is noting that it is iterating over an array and only hits the numeric keys.

df is not a numeric key.

Nothing strange. Params is just an object (of builtin type Array).

console.log('params is empty: '+(params == '')); //result of Array.toString on empty array = ""

console.log('params: '+params); //result of Array.toString on empty array = ""

console.log('df: '+params['df']); //if params is an object and you do params.df='15.03.2012' then params['df']='15.03.2012'. 

$.each(params, function(p_name, p_val){
    console.log(p_name+': '+p_val);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM