gpt4 book ai didi

javascript - javascript 中 if 语句被跳过

转载 作者:行者123 更新时间:2023-12-03 05:14:01 25 4
gpt4 key购买 nike

我正在编写一个基本应用程序,以从参数中获取值并显示它们。我有两个文件:

  1. APP.js

    console.log('application launching');

    const fs = require('fs');
    const yarg = require('yargs');
    const node = require('./node.js')

    var command = yarg.argv;

    if (command === '3' ) {
    console.log("adding note");
    node.addnote(argv.name,argv.title);
    }
    else {
    console.log('invalid');
    }
  2. node.js

    console.log("im up")

    var addnote = (name,title) => {
    console.log('Welcome', title, name);
    };

    module.export = {
    addnote
    }

这是我传递参数时得到的输出:

Admins-Mac:node admin$ node app.js --3 Tony Mr

application launching

im up

invalid

如果我的知识是正确的,输出一定是Welcome Mr Tony

我无法找出错误。

最佳答案

yargs 给你一个参数对象。所以你需要检查

if (command[3]) {
// ...
}

但是,我们会在这里遇到错误

node.addnote(argv.name,argv.title);

因为您没有传递任何内容,并且 argv.name 和 argv.title 均未定义。

所以给出这个命令:

node app.js --3 --name=Tony --title=Mr

您需要此代码:

let command = yarg.argv;
if (command[3]) {
console.log("adding note");
addnote(command.name,command.title);
}

第三,你不需要nodejs。这是你的环境。相反,您需要要求文件保存第二个代码块。

const addnote = require("./2nd.js");

假设您的文件名为 2nd.js 并且位于同一文件夹中。

<小时/>

总结一下(您的代码中存在许多其他错误),这是对您的代码的有效重写:

1st.js:

const fs = require('fs');
const yarg = require('yargs');
const addnote = require("./2nd.js");

let command = yarg.argv;

if (command[3]) {
console.log("adding note");
addnote(command.name, command.title);

}

else {
console.log('invalid');
}
<小时/>

2nd.js:

let addnote = (name,title)=>{
console.log(`Welcome, ${title} ${name}`);
};

module.exports = addnote;

Run with

node 1st.js --3 --name=Tony --title=Mr

关于javascript - javascript 中 if 语句被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com