假设您要运行if / else条件

我正在尝试运行此代码以根据某些条件打印一个值,但它仅打印一个值。这是代码:


let instagramlikes;

let sitetraffic;

let dailytraffic;


function clientwidgets(x) {

  if (x === instagramlikes) {

    console.log("This is A");

  } else if (x === sitetraffic) {

    console.log("This is B");

  } else if (x === dailytraffic) {

    console.log("This is C")

  }

};


console.log(clientwidgets(instagramlikes));

console.log(clientwidgets(sitetraffic));

console.log(clientwidgets(dailytraffic));


慕桂英546537
浏览 141回答 2
2回答

收到一只叮咚

从技术上讲, JavaScript没有枚举。如果不初始化变量,则将其初始化为未定义。也就是说,以下两个语句完全相同:let instagramlikes;let instagramlikes = undefined并且在您的函数中,您基本上传入x和undefined。如果这则检查x === instagramlikes其翻译为undefined === undefined,这将是true。为了模拟枚举,您可以尝试将变量设置为某个值,如下所示:const instagramlikes = 'instagramlikes';const sitetraffic = 'sitetraffic';const dailytraffic = 'dailytraffic';function clientwidgets(x) {  if (x === instagramlikes) {    return "This is A";  } else if (x === sitetraffic) {    return "This is B";  } else if (x === dailytraffic) {    return "This is C";  }};console.log(clientwidgets(instagramlikes));console.log(clientwidgets(sitetraffic));console.log(clientwidgets(dailytraffic));虽然它不一定是字符串,但是您可以使用数字或任何对象。如果您要定位的环境支持,则可以使用符号(例如Symbol)。Symbol的每个实例都是唯一的,因此与之进行的比较===应该完美无缺。const instagramlikes = Symbol();const sitetraffic = Symbol();const dailytraffic = Symbol();function clientwidgets(x) {  if (x === instagramlikes) {    return "This is A";  } else if (x === sitetraffic) {    return "This is B";  } else if (x === dailytraffic) {    return "This is C";  }};console.log(clientwidgets(instagramlikes));console.log(clientwidgets(sitetraffic));console.log(clientwidgets(dailytraffic));

当年话下

尝试为每个不同的选项分配一个唯一的值。let instagramlikes = 1;let sitetraffic = 2;let dailytraffic = 3;function clientwidgets(x){  if (x === instagramlikes){    console.log("This is A");  } else if (x === sitetraffic){    console.log("This is B");  } else if (x === dailytraffic){    console.log("This is C")  }}clientwidgets(instagramlikes);clientwidgets(sitetraffic);clientwidgets(dailytraffic);我将创建一个对象枚举来也包含所有类型:const TYPE = {  INSTAGRAM_LIKES:1,  SITE_TRAFFIC:2,  DAILY_TRAFFIC:3}然后像这样打电话clientwidgets(TYPE.INSTAGRAM_LIKES);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript