简体   繁体   English

奇怪的js数组行为

[英]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 . 大概是(因为您显示的是那样,所以必须使用预定义的变量,所以除非通过对您执行的测试得出结论,否则我们无法知道其中的实际内容),因为params数组而不是对象

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. $.each注意到它正在数组上迭代,并且只命中了数字键。

df is not a numeric key. df不是数字键。

Nothing strange. 没什么奇怪的 Params is just an object (of builtin type Array). 参数只是一个对象(内置类型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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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