我编写了这段代码示例,以了解“Name”中具有特定值的元素的索引位置。我的变量数据包含这些元素的列表。
var data = {"Attributes":[
{"Name":"bedrooms","Value":"4"},
{"Name":"bathrooms","Value":"2"},
{"Name":"property_type","Value":"House"},
{"Name":"rateable_value","Value":"$780,000"},
{"Name":"price","Value":"Price by negotiation"},
{"Name":"location","Value":"13"},
{"Name":"district","Value":"Queenstown-Lakes"},
{"Name":"suburb","Value":"Lower Shotover"},
{"Name":"region","Value":"Otago"},
{"Name":"floor_area","Value":"254m²"},
{"Name":"land_area","Value":"1690m²"},
{"Name":"property_id","Value":"CBM959"},
{"Name":"in_the_area","Value":"playground"},
{"Name":"parking","Value":"Large double garage"}
]}
find_index = function(list, str){
list.each(function(index, value){
console.log("Comparing "+value.Name+" with "+str);
if(value.Name == str){
return index;
}
});
};
console.log(find_index($(data.Attributes), "bedrooms"))
当我执行此代码时,它会在日志中打印所有比较,然后返回“undefined”。我期待的是在比较成功时停止迭代,并返回0,这是名为“卧室”的元素的位置。
这里发生了什么?我该如何解决呢?
答案 0 :(得分:3)
您需要从函数中返回值。
尝试
find_index = function(list, str){
var idx;
list.each(function(index, value){
console.log("Comparing "+value.Name+" with "+str);
if(value.Name === str){
idx = index;
return false; //Exit out of the loop after the match
}
});
return idx;
};
.each
循环中的返回值用作布尔值以退出或继续循环。
此外,您不需要创建jquery对象,您可以在数组上使用$.each
,如下所示:
find_index = function(list, str){
var idx;
$.each(list, function(index, value){
if(value.Name === str){
idx = index;
return false; //Exit out of the loop after the match
}
});
return idx;
};
console.log(find_index(data.Attributes, "bedrooms"));
你可以更好地简化这一点,特别是如果你想获得多个匹配。但是,没有办法打破地图:
find_index = function(list, str){
return $.map(list, function(val, idx){
if(val.Name === str) return idx;
})[0]; //for multiple matches remove 0
};
console.log(find_index(data.Attributes, "district"));
答案 1 :(得分:1)
Incase,字符串比较失败尝试使用localeCompare;这就是为了完全匹配字符串而进行救援。
find_index = function(list, str){
var localIndex;
list.each(function(index, value){
console.log("Comparing "+value.Name+" with "+str + index);
if(str.localeCompare(value.Name) == 0)
{
localIndex = index;
return false;
}
});
return localIndex;
};
console.log(find_index($(data.Attributes), "bedrooms"));
答案 2 :(得分:0)
除非您返回false,否则每个函数都不会停止(中断)。您可以为变量分配匹配的索引,然后返回false。