2017-09-04 207 views
1

有人能告诉我为什么每次我想检查一个键是否可用于我的数组中,我得到的结果是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>

+3

你不能在obj'检查属性'“名”对一个数组 – RomanPerekhrest

+0

嘛,'obj'是一个数组,尽管它的名字,而数组没有命名密钥。这个数组由对象组成,你可以在obj [0]中做''value'来检查数组中的第一项是否为对象,它是否具有键“值”等。 – adeneo

+1

因为你试图找到数组元素的一个键。这是行不通的。考虑使用:obj.filter((e)=> {return e.value == 10})。length> 0'如果你正在为一个值为10的元素打结。 – Bellian

回答

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>

3

要检查我的例子中,如果“价值”的数组中存在,而不是在你的数组的元素。要正确检查数组元素中是否存在“值”,您需要寻址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); 
+0

是的但我不想检查第一个对象。我想检查我的对象内的每个名字。 – Rotan075

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

+1

.filter(..)。长度在这里是不必要的。它总是有O(n),而.some(..)只有O(n)最坏的情况。 –

+0

@Jonasw没错,谢谢你提醒我。 –

1

的问题是,您要检查是否存在阵列上的关键,而不是在阵列内的对象,从而有望为它们穿上”这些密钥不匹配t存在于阵列上。

如果你想检查数组内的任何物体都有特定的键,然后你可以用一个简单的循环做到这一点:

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>"); 
0

操作检查:可以做到这一点。你的阵列具有以下键:

0,1 

所以

0 in obj 

是真实的。

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'));

1

你可以试试这个。

var obj = new Object(); 
obj.name='t1'; 
obj.value='t2'; 

obj.hasOwnProperty('value'); // Return true if exist otherwise false 
+0

你也可以,: 函数查找(名称){ 为(VAR I = 0,LEN = arr.length; I

1

in运营商检查它被称为该对象的属性键名称。您可以将它用于您推入数组中的对象,或者将它用于数组索引。

// 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)
<p><span id='passed'>0</span> tests passed</p>

1

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

// 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