通过推送值检查数组中是否存在键

时间:2017-09-04 14:52:15

标签: javascript

有人可以告诉我为什么每次我想检查我的数组中的密钥是否可用时,我得到的结果是false?请参阅下面的示例

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });

//var inobject = "name" in obj; // result: false
//var inobject = "test1" in obj; // result: false
//var inobject = "10" in obj; // result: false
var inobject = "value" in obj;

$('body').append("<p>"+ inobject + "</p>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

9 个答案:

答案 0 :(得分:3)

您正在检查&#34;值&#34;存在于数组中而不存在于数组的元素中。要正确检查&#34;值&#34;存在于需要解决obj[i]的数组元素中。像这样:

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });
var inobject = "value" in obj[0];
console.log(inobject);

答案 1 :(得分:1)

因为"value" in obj不是你在数组中检查值的存在的方式,并且你有一个对象数组,这意味着你必须检查数组元素的存在而不是数组本身,这是你是怎么做到的:

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });
var inobject = obj.some((a) => "value" in a);
console.log(inobject); // true, means it's there

如果要获取具有键“值”的元素,请使用:

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });
obj.push({ name: "test2", AnotherKey: "60" });
var objects = obj.filter((a) => "value" in a);
console.log(objects); // test1 and test2

答案 2 :(得分:1)

问题是您正在尝试检查数组上是否存在密钥,而不是数组中的对象,因此预期这些密钥不匹配,因为它们不存在于数组中。

如果您正在尝试检查数组中的任何对象是否具有特定键,那么您可以通过一个简单的循环来执行此操作:

var found = false;
var search = "value";
for(var i = 0; i < obj.length; i++){
    if(search in obj[i]){
        found = true;
        break;
    }
}

或者将它分成一个很好的功能:

function doesKeyExist(var arr, var key){
    for(var i = 0; i < obj.length; i++){
        if(key in obj[i])
             return true;
    }
    return false;
}

var inobject = doesKeyExist(obj, "value");
$('body').append("<p>"+ inobject + "</p>");

如果要查找属性的,可以执行以下操作:

function doesValueExistForKey(var arr, var key, var search){
    for(var i = 0; i < obj.length; i++){
        if(key in obj[i] && obj[i][key] === search)
             return true;
    }
    return false;
}

var inobject = doesValueExistForKey(obj, "name", "test1");
$('body').append("<p>"+ inobject + "</p>");

答案 3 :(得分:1)

您只能搜索数组的键或值,如下所示:

var obj = new Array(),
  el1, el2

obj.push(el1 = { name: "test1", value: "10" });
obj.push(el2 ={ name: "test2", value: "40" });

$('body').append("<p>check for key 1: "+ (1 in obj) + "</p>");
$('body').append("<p>check for element el1: "+ (obj.indexOf(el1) >= 0) + "</p>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

如果您正在搜索符合其他条件的数组中的元素,则必须执行以下操作:

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });

// direct object access
var inobject = obj.filter((e)=>{ return 'value' in e && e.value == 10}).length > 0;

// deconstruct elements for better readability (WARNING: object deconstruction is not supported in all browsers yet!)
var inobject2 = obj.filter(({name, value})=>{ return 'value' !=undefined && value == 10}).length > 0;

$('body').append("<p>Search for element with value = 10: "+ inobject + "</p>");
$('body').append("<p>Search for element with value = 10: "+ inobject2 + "</p>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 4 :(得分:1)

如果要在集合中的任何对象(第一级)中找到一个键,那么就不要这样做了 "value" in obj;您可以obj.some(e=> "value" in o);

//name is obj but its actually a array
var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });


function checkForKey(list, key) {
   return list.some(e => key in e);
}

console.log('Key [name]:', checkForKey(obj, 'name'));
console.log('Key [age]:', checkForKey(obj, 'age'));
console.log('Key [value]:', checkForKey(obj, 'value'));

如果您正在寻找任何级别,在数组或对象内部递归,那么试试这个,(性能效率不高但易于操作)

var obj = new Array();
obj.push({ name: "test1", value: "10" });
obj.push({ name: "test2", value: "40" });

function checkForKeyNested(list, key) {
    try {
    JSON.parse(JSON.stringify(list), function(k, v){
        if(key===k) {
            flag=true;
            throw 0;
        }
        return v;
    });
    } catch(ex) { return true;}
    return false;
}

console.log('Key [name]:', checkForKeyNested(obj, 'name'));
console.log('Key [age]:', checkForKeyNested(obj, 'age'));
console.log('Key [value]:', checkForKeyNested(obj, 'value'));

答案 5 :(得分:1)

你可以试试这个。

root/
    1/
     1.bmp
     2.bmp
     3.bmp
     4.bmp
     ...
    2/
     1.bmp
     2.bmp
     3.bmp
     4.bmp
    ....
    3/
     1.bmp
     2.bmp
     3.bmp
     4.bmp
     ....

答案 6 :(得分:1)

in运算符检查调用它的对象的属性键名。您可以在推入阵列的对象上使用它,或者将它与数组索引一起使用。

&#13;
&#13;
// a little nano-sized test suite made on the fly :)
const passed = document.getElementById('passed')
const assert = test => {
  if (!test) throw 'invalid assertion'
  passed.innerText = +passed.innerText + 1
}

// creates an Object that inherits from Array.prototype
var obj = new Array()

// Append an object {name, value} to the array
// 
obj.push({
  name: 'test1',
  value: 10
})

// Add a property to the array-object called value
obj.value = 40

assert('name' in obj === false)
assert('value' in obj === true)
assert(0 in obj === true)
assert('name' in obj[0] === true)
&#13;
<p><span id='passed'>0</span> tests passed</p>
&#13;
&#13;
&#13;

答案 7 :(得分:1)

您正在使用一组对象。有几种方法可以做到这一点,但是让我们简单地创建一个lookup和lookupAll函数并使用它:(它们都返回对象数组),其他方法返回索引和索引数组 - 如果排序则更改。请注意,即使在非常丑陋的老浏览器(如IE6)中也可以。

&#13;
&#13;
// create a namespace for my functions
var myApp = myApp || {};
myApp.arrayObj = {
  indexOf: function(myArray, searchTerm, property) {
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
  },
  indexAllOf: function(myArray, searchTerm, property) {
    var ai = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) ai.push(i);
    }
    return ai;
  },
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAll: function(myArray, property, searchTerm) {
    return this.lookup(myArray, searchTerm, property, false);
  }
};

var myobj = [{ name: "friend", value: "17" }];// better than new Array()
myobj.push({ name: "test1", value: "10" });
myobj.push({ name: "test2", value: "40" });
console.log(myobj);
// array of all matches
var allones = myApp.arrayObj.lookupAll(myobj, "test1", "name");
console.log(allones.length);// 1

// returns array of 1 
var firstone = myApp.arrayObj.lookup(myobj, "friend", "name",true);
console.log(firstone[0].value);//17
&#13;
&#13;
&#13;

答案 8 :(得分:0)

in 运算符检查。您的数组具有以下键:

0,1

所以

 0 in obj 

是真的。