使用长度属性写If语句

JS: Using Length Property to Write If Statement

本文关键字:If 语句 属性      更新时间:2023-09-26

我对JS很陌生,所以请对我宽容一点。我有这个数组在一个变量中,我试图找到一个更好的方法来写if语句。因此,如果变量中的名称增长,我不需要更改if语句,因为它不会硬编码。

var names = ["beth", "barry", "debbie", "peter"]
if (names[0] && names [1] && names [2] && names [3] {
    Do something...
}

有些东西告诉我,我需要使用.length属性,但我不知道如何在该语句中正确使用它。类似以下语句:

if (names[i] * names.length) { 
    Do something...
}

我知道那是错的。我认为需要找到每个的索引,并通过它循环,以确保循环不超过数组中的值的数量。

任何帮助都是感激的。提前感谢!

更新:一些用户提醒我,我的问题可能不那么清楚。我在这里设置了一个CodePen (http://codepen.io/realph/pen/KjCLd?editors=101),可以解释我想要实现的目标。

注:怎样才能不重复3次呢?

您可以使用every来测试每个元素是否满足某些条件:

if (names.every(function (name) { return name })) {
  // Do Something
}

every将在发现第一个非真元素时自动停止测试,这可能是一个很大的优化,取决于数组的大小。

传统上,您只需遍历数组并测试每个元素。您可以使用forEach或简单的for循环来做到这一点。当发现非真元素时,可以通过从forEach回调返回false来执行同样的提前终止操作。

var allTrue = true;
names.forEach(function (name) {
  return allTrue = allTrue && name;
});
if (allTrue) { 
  // Do something...
}

请用英文描述您想要完成的工作。下面的答案假设您只是想迭代一个名称列表,并对每个名称做一些处理。

你想使用for循环。

var names = ["beth", "barry", "debbie", "peter"]
for (var i=0; i<names.length; i++) {
    // access names[i]
}

最好的跨浏览器解决方案是使用传统的for循环。

var names = ["beth", "barry", "debbie", "peter"],
    isValid = true,
    i;
for (i = 0; i < names.length; i++) {
    isValid = isValid && names[i];
}
if (isValid) {
    // do something
}

你可以试试;

    var checkCondition = true;
    for(var i = 0; i<names.length; i++){
      if(names[i] !== something) {
         checkCondition = false;
         break;
      } 
    }
    if(checkCondition){
        //Do what ever you like if the condition holds
    }else{
        // Do whatever you like if the condition does NOT holds
    }

如果我没理解错的话,你需要这样的东西

var names = ["beth", "barry", "debbie", "peter"];
var notUndefinedNames = names.filter(function(el){return el !== undefined;});
// if all
if (names.length === notUndefinedNames.length) console.log("You're all here. Great! Sit down and let's begin the class.");
// if one or less
else if (notUndefinedNames.length <= 1) console.log("I can't teach just one person. Class is cancelled.");
else console.log("Welcome " + notUndefinedNames.join(', '));