[英]Find value in associative array
I have created an associative array using following function. 我使用以下函数创建了一个关联数组。
function checkEmpty(){
var sizes = new Array();
var validate = new Array();
$j('div.option-fields').each(function(){
if($j(this).attr('id')) {
sizes.push($j(this).attr('id'));
}
});
for(var i=0; i< sizes.size(); i++){
$j("#"+sizes[i]+' input[type=text]').each(function(){
if($j(this).val()){
//validate.push(true);
validate[sizes[i]] = true;
}else{
//validate.push(false);
validate[sizes[i]] = false;
}
});
}
}
which return [size-278: true, size-287: true] 返回[size-278:true,size-287:true]
Now I want to search whether this result contain false in value or not, or whether all value with different indexes are same or not. 现在,我要搜索此结果是否包含错误的值,或者所有具有不同索引的值是否相同。
I used inArray but it is giving -1 every time. 我使用了inArray,但每次都给出-1。
It is better that validate
will be an Hash rather than Array validate
最好是哈希而不是数组
Search Associative Arrays here: https://www.w3schools.com/js/js_arrays.asp 在此处搜索关联数组: https : //www.w3schools.com/js/js_arrays.asp
so declare it like this: 所以这样声明:
var validate = {};
Than you will get something like this {size-278: true, size-287: true} 比您将得到以下内容{size-278:true,size-287:true}
And you can look for false value like this: 您可以这样查找假值:
var validate = {'size-278': true, 'size-287': true}; var values = Object.values(validate); console.log(values.indexOf(false)); var validate = {'size-278': true, 'size-287': true}; var values = Object.values(validate); console.log(values.indexOf(true));
Notice that Object.values
may not be supported in older browser 请注意,较旧的浏览器可能不支持
Object.values
To search for an a value within an associative array, you do it like so: 要在关联数组中搜索一个值,您可以这样做:
listOfLanguagesAndTheirSubtags = {"Afrikaans" : "AF", "Dansk" : "DA", "Deutsch": "DE", "English": "EN", "Italiano" : "IT" };
var values = Object.values(listOfLanguagesAndTheirSubtags);
var subtagToFind = "AF";
if(values.includes(subtagToFind))
{
console.log('value is found');
}
else
{
console.log('value NOT found');
}
To search whether all values with different indices are the same or not, you can go further like so: 要搜索具有不同索引的所有值是否相同,可以进一步进行如下操作:
var numberOfOccurencesOfSubtag = values.filter(function(value){
return value === subtagToFind;}).length
if(numberOfOccurencesOfSubtag === values.length)
{
console.log("All values with different indices are the same");//... as subtagToFind
}
else
{
console.log("All values with different indices are NOT the same");//... as subtagToFind
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.