微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在for循环通过对象时忽略一个值?

如何解决如何在for循环通过对象时忽略一个值?

我正在使用 for loop 循环遍历一个对象,我想在循环时忽略一些特定的值。

这段代码负责循环遍历我的对象:

let acceptAll = function (rawContent){
   for(let i in rawContent)
   if(!rawContent[i]) return false;
   return true
};

我想在循环时忽略 rawContent 中的一个值,这可能吗?

非常感谢!

解决方法

您有几个选择:

  1. if continue

  2. if 自身

这是if continue

for (let i in rawContent) {
    if (/*...you want to ignore it...*/) {
        continue; // Skips the rest of the loop body
    }
    // ...do something with it
}

或单独使用 if

for (let i in rawContent) {
    if (/*...you DON'T want to ignore it...*/) {
        // ...do something with it
    }
}

旁注:这是一个 for-in 循环,而不是一个 for 循环(即使它以 for 开头)。 JavaScript 具有三个以 for 开头的独立循环结构:

  • 传统的 for 循环:

    for (let i = 0; i < 10; ++i) {
          // ...
    }
    
  • for-in 循环:

    for (let propertyName in someObject) {
          // ...
    }
    

    (如果您从不更改循环体中 propertyName 中的值,则可以使用 const 代替 let。)

  • for-of 循环:

    for (let element of someIterableLikeAnArray) {
          // ...
    }
    

    (如果您从不更改循环体中 element 中的值,则可以使用 const 代替 let。)

,

我猜您正在搜索 continue 关键字:

let array = [1,2,3,4]

for(let i of array){
    if(i === 2) continue
  console.log(i)
}

,

您可以维护要忽略的值数组。例如

const valuesToIgnore = [1,5,15,20]
let acceptSome = (rawContent) => {
    for (let i of rawContent) {
        if (valuesToIgnore.includes(i)) {
        // These are the values you want to ignore
            console.log('Ignoring',i)
        } else {
        // These are the values you do not want to ignore
            console.log('Not Ignoring',i)
        }
    }
}

// And you invoke your function like this -

acceptSome([1,10,20,25])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。