【问题标题】:Why isn't this javascript returning the expected code?为什么这个 javascript 不返回预期的代码?
【发布时间】:2021-04-13 00:36:24
【问题描述】:
let myName = 'vincenzo';
if (myName !== String) {
console.log('this is not a string');
} else if (myName.length % 2 === 0){ 
console.log(even);
} else if (myName.length % 2 !== 0){
console.log(odd);
}

谁能解释为什么这只返回“这不是一个字符串”?它不应该返回“偶数”吗?我不确定我哪里出错了

【问题讨论】:

  • 提示:typeof.
  • 提示:typeof myName !== 'string'
  • 您应该避免在else if 中指定唯一的其他逻辑可能性。与if (x == 1) 一样,else 是自动 的逻辑逆,例如if (x != 1)。不要指定明显的。

标签: javascript string variables logging operators


【解决方案1】:

你只需要清理这段代码:

function determine(str) {
  if (typeof(str) !== 'string') {
    console.log('this is not a string');
  } else if (str.length % 2 === 0) { 
    console.log('even');
  } else {
    console.log('odd');
  }
}

determine('vincenzo');

【讨论】:

  • @iota 正在努力。
【解决方案2】:
const determinfun=(MyName)=>{
if (type of MyName !== String) {
console.log('this is not a string');
} else if (MyName.length % 2 === 0){ 
    console.log('even');
} else if (MyName.length % 2 !== 0){
console.log('odd');
}
}

determinfun('vincenzo');

请使用运算符类型类型的 MyName !== String

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2017-06-08
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多