首页 > 解决方案 > 代码在 Visual Studios 代码 (VScode) 中不起作用

问题描述

再会,

一天前,我刚刚在我的计算机中安装了 Visual Studio Code (vscode)。我是 JavaScript 新手,但我遇到了一些代码并想在其中进行测试。

如果我使用 Chrome 控制台,这行代码运行良好,但目前我将它放在我刚刚安装的 vscode 中,它没有给出任何响应。

这是我正在测试的代码:

var fruit = 'Banana';
fruit.slice(0, 2);
// Outcome: "Ba"

但是,如果我将代码更改为其他内容,请说:

var fruit = "Banana";
console.log(fruit.slice(0, 2));

然后它工作,

有人可以告诉我为什么第一行代码在 Visual Studio Code (vscode) 中不起作用吗?

谢谢,曼尼

标签: javascriptvisual-studio-code

解决方案


该代码有效。fruit.slice(0, 2);返回“Ba”,但您没有将返回的值分配给变量或对其进行任何操作,这就是您可能认为代码不起作用的原因。

var fruit = 'Banana';
var sliced = fruit.slice(0, 2);
// sliced is now equal to 'Ba'. 
// If your program ended here, you wouldn't see anything on the console though.
// So far, this is equivalent to your first example.

console.log(sliced);
// Now we're just logging the value of sliced, and we will see 'Ba' in the console.
// Now, this block of code is equivalent to your second example.

推荐阅读