简体   繁体   English

在 JavaScript 中附加条件作为数组长度

[英]Append a condition as array length in JavaScript

How can I make a condition by array length cleverly in JavaScript?如何在 JavaScript 中巧妙地通过数组长度创建条件?

Please see below :请参阅以下内容:

var value = ['a','b','c'];

var array0 = ['apple'];
var cond0 = value.indexOf(array0[0]) == -1 ;

var array1 = ['apple', 'banana'];
var cond1 = value.indexOf(array1[0]) == -1 && value.indexOf(array1[1]) == -1 ;

// On the same way, 

var array2 = ['apple', 'banana', 'kiwi'];
var cond2 = value.indexOf(array2[0]) == -1 && value.indexOf(array2[1]) == -1 && value.indexOf(array2[2]);

Simply I want to append to && conditions as the array's length.只是我想附加到&&条件作为数组的长度。 How can I make a 'cond' simply?我怎样才能简单地制作一个“条件”?

I don't know a simple way, so I append conditions manually.我不知道一个简单的方法,所以我手动附加条件。

But I think this is not a good way, How can I do it cleverly?但我认为这不是一个好方法,我该如何巧妙地做到这一点?

You can create a function to validate if value is absent or not您可以创建一个函数来验证值是否不存在

function notContains(values, array) {
   for(var i = 0; i < values.length; i++) {
       for(var j = 0; i < array.length; i++) {
           if(array[j].indexOf(values[i]) > -1) {
              return false;
           }
       }
   }
   return true;
}
var values = ['a','b','c'];
var cond0 = notContains(values, ['apple']);
var cond1 = notContains(values, ['apple', 'banana']);
var cond2 = notContains(values, ['apple', 'banana', 'kiwi']);

following should do the trick.以下应该可以解决问题。

var array2 = ['apple', 'banana', 'kiwi'];
var cond2 = true;
for(var idx = 0; idx < array2.length; idx++) {
  cond2 = cond2 && (value.indexOf(array2[idx]) == -1);
  if(!cond2) {
     // its already false, no need to iterate
     break;
  }
}

you can try looping through the array:您可以尝试遍历数组:

array2.forEach(function(item){
   if(value.indexOf(item) > -1){
       ....
   }
));

Georg's solution is very good but i guess this takes it one step further. Georg 的解决方案非常好,但我想这更进一步。 You can simply do like this.你可以简单地这样做。

 var value = ['a','b','c'], array2 = ['apple', 'banana', 'kiwi']; check = array2.reduce((p,c) => p = p || value.includes(c),false) console.log(check);

to answer this: 'How can I make a condition by array length cleverly in JavaScript?'回答这个问题: “如何在 JavaScript 中巧妙地通过数组长度创建条件?”

I think you could do this:我认为你可以这样做:

var stop = 0;
while(stop < value.length){
  if(condition){
    // do something
  }
 stop++;
}

An optimized solution using Array.some function(if the callback function returns a truthy value for any array element):使用Array.some函数的优化解决方案(如果回调函数返回任何数组元素的值):

var value = ['a','b','c'],
    array2 = ['apple', 'banana', 'kiwi'];

var cond2 = !array2.some((v) => value.indexOf(v) !== -1);

console.log(cond2);  // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM