我试图查看数组中是否存在某个键,如果存在,则返回它的值:
if(jQuery.inArray(live_ids.grade, item.SizePrice) !== -1) {
console.log(item.SizePrice);
}
这将返回:
{"8":"15.00","7":"20.00","1":"6.00","6":"11.00","2":"7.00","3":"8.00","4":"9.00","5":"10.00","11":"20.00","9":"10.00","10":"15.00","13":""}
现在,live_ids.grade
= 9,所以我希望能够返回10.00
...我该怎么做?
答案 0 :(得分:2)
在这里检查数字是否在obj中,而不是执行else show error。
var obj = {
"8":"15.00",
"7":"20.00",
"1":"6.00",
"6":"11.00",
"2":"7.00",
"3":"8.00",
"4":"9.00",
"5":"10.00",
"11":"20.00",
"9":"10.00",
"10":"15.00",
"13":""
};
var number = 9;
if(number in obj){
alert(obj[number])
} else {
alert("This number does not exists")
}

答案 1 :(得分:0)
item.SizePrice
似乎是Object
,而不是Array
。您可以在对象上使用for..in
循环,break
在console.log()
调用后的循环
var items = {
"8": "15.00",
"7": "20.00",
"1": "6.00",
"6": "11.00",
"2": "7.00",
"3": "8.00",
"4": "9.00",
"5": "10.00",
"11": "20.00",
"9": "10.00",
"10": "15.00",
"13": ""
},
n = 9;
for (var prop in items) {
if (items[n]) {
console.log(items[n]);
break;
}
}
答案 2 :(得分:0)
这是你的解决方案......
<script type="text/javascript">
var a={"k1": 100, "k2": 200, "k3": 300};
var ky=prompt("enter key :");
for (var k in a){
if (a.hasOwnProperty(k)) {
if(k==ky){
alert("Key is " + k + ", value is" + a[k]);
}
}
}
</script>