问题描述
我一直在尝试解决有关hackerrank的模板文字问题。它在我的本地IDE上运行良好,但在Hackerrank IDE上却报错。 这是代码2加两个数字并使用模板文字打印结果。
const sum = () => {
let a=1;
let b=2;
console.log(`The sum of ${a} and ${b} is ${a + b}`);
}
module.exports = {sum}
但是它会产生以下错误。
npm WARN template-literals@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
audited 522 packages in 6.264s
found 611 vulnerabilities (378 low,233 high)
run `npm audit fix` to fix them,or `npm audit` for details
> template-literals@1.0.0 test /projects/challenge
> mocha test --reporter mocha-junit-reporter
The sum of 1 and 2 is 3
npm ERR! Test Failed. See above for more details.
解决方法
我想添加我的观点。
const sum = (a,b) => {
return `The sum of ${a} and ${b} is ${a + b}`;
}
module.exports = {sum}
,
这是一个简单的例子。
const sum = (a = 1,b = 2) => {
return `The sum of ${a} and ${b} is ${a + b}`;
}
这是解释。
const sum = Create a variable named `sum`.
(a = 1,b = 2) => { Create an arrow function,with variables `a` and `b`,with defaults of 1 and 2 respectively.
return ` Return a string. In addition to " and ',a backtick will create a string,but with benefits!
${a} Interpolate the variable `a` into the string.
${b} Interpolate the variable `b` into the string.
${a + b} Interpolate the expression of `a + b`.
`; End the string.
这是一个没有插值的代码示例。
const sum = (a = 1,b = 2) => {
return 'The sum of ' + a + ' and ' + b + ' is ' + (a + b);
}