我有一个像[HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"]
这样的数组。我从控制台得到了这个。
我试图找出如下所示的价值
var sku = skus_colorcode.indexOf('9620');
console.log(sku);
但它返回-1。
为什么我得到这个结果?
答案 0 :(得分:4)
您的代码根本无效。数组是元素列表,没有键。 你必须使用一个对象,如下所示:
var skus_colorcode = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"}
要查找与" 9620"对应的键(HT ....),请尝试以下代码:
var keys = Object.getOwnPropertyNames(skus_colorcode), key;
for(var i = 0; i < keys.length; i++)
if(skus_colorcode[keys[i]] === "9620") {
key = keys[i];
break;
}
// The right key is into the "key" variable
console.log(key); // says "HT2787Z2UK"
答案 1 :(得分:1)
试试这个
function arraySearch(arr,val) {
for (var key in arr) {
this_val = array[key];
if(this_val == val){
return key;
break;
}
}
}
答案 2 :(得分:0)
这应该是
var obj = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"}
for (var key of obj) {
if (obj[key] == "9620"){
return key;
}
}
return false
答案 3 :(得分:0)
我同意“hemnath mouli”代码应该像他写的那样:
<script type="text/javascript">
keys = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"};
function getIndexOf(obj,value){
var count = 0;
for (var i in obj){
if(obj[i] == value.toString()){
return "index[" + count + "]:" + obj[i] + " = " + i;
//return what you want
}
count ++;
}
}
</script>
然后你得到了值
<script type="text/javascript">
alert(getIndexOf(keys,9621));
</script>
请你发一段代码来检索@ClementNerma的值,即使我同意你这不是更有效的方法。
我只是不想“低估”这个问题。
或者如果您想将对象转换为数组:
<script type="text/javascript">
keys = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"};
function obj2Array(obj){
k = [];
for (var i in obj){
k.push(obj[i]);
}
return k;
}
</script>
<script type="text/javascript">
arr = obj2Array(keys);
alert (arr[2]);
</script>
@abu abu
答案 4 :(得分:-2)
您可以使用Jquery:
abstract class Car
{
public abstract double MaximumSpeed { get; }
}
class Minivan : Car
{
public override double MaximumSpeed { get { return 100.0; } }
}