简体   繁体   English

为什么if语句不返回boolean和object类型的值?

[英]Why won't the if-statements return values of type boolean and object?

I'm curious as to why the else if statements in the filter method do not return anything: 我很好奇为什么filter方法中的else if语句不返回任何内容:

var moveZeros = function (arr) {
  const nonZeros = arr.filter(value => {
    if (value !== 0) return value
    else if (typeof value === 'boolean') return value
    else if (typeof value === 'object') return value
  })

  const zeros = arr.toString().match(/0/g).map(Number)

  const newArr = nonZeros.concat(zeros) 

  return newArr
}

Additionally, I would also like to know why I get a similar effect when I try to filter out zeros from an array: 另外,我也想知道为什么当我尝试从数组中滤除零时得到类似的效果:

const zeros = arr.filter(value => {
  if (value === 0) return value
})

Here is a sample array to test the function: 这是测试功能的示例数组:

[ 0, 1, null, 2, false, 1, 0 ]

Thank you for any help! 感谢您的任何帮助!

You don't need to return value in the filter method, return the boolean which should be true if the value should be selected, like so: 您不需要在filter方法中返回值,而应返回布尔值,如果应选择该值,则该值为true,如下所示:

 var moveZeros = function (arr) { // also when you use !== 0, you don't need to check the type as it compares type const nonZeros = arr.filter(value => value !== 0) const zeros = arr.filter(value => value === 0) const newArr = nonZeros.concat(zeros) return newArr } console.log(moveZeros([ 0, 1, null, 2, false, 1, 0 ])); 

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

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