在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
当前回答
我认为第一种方法(多个变量)是最好的,否则你就会得到这样的结果(来自使用KnockoutJS的应用程序),这在我看来很难理解:
var categories = ko.observableArray(),
keywordFilter = ko.observableArray(),
omniFilter = ko.observable('').extend({ throttle: 300 }),
filteredCategories = ko.computed(function () {
var underlyingArray = categories();
return ko.utils.arrayFilter(underlyingArray, function (n) {
return n.FilteredSportCount() > 0;
});
}),
favoriteSports = ko.computed(function () {
var sports = ko.observableArray();
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
sports.push(a);
}
});
});
return sports;
}),
toggleFavorite = function (sport, userId) {
var isFavorite = sport.IsFavorite();
var url = setfavouritesurl;
var data = {
userId: userId,
sportId: sport.Id(),
isFavourite: !isFavorite
};
var callback = function () {
sport.IsFavorite(!isFavorite);
};
jQuery.support.cors = true;
jQuery.ajax({
url: url,
type: "GET",
data: data,
success: callback
});
},
hasfavoriteSports = ko.computed(function () {
var result = false;
ko.utils.arrayForEach(categories(), function (c) {
ko.utils.arrayForEach(c.Sports(), function (a) {
if (a.IsFavorite()) {
result = true;
}
});
});
return result;
});
其他回答
第二种方法的主要问题是,到目前为止还没有IDE支持这种风格。 你不能折叠这些结构。
我认为这是个人喜好的问题。我喜欢用下面的方法做这件事:
var /* Variables */
me = this, that = scope,
temp, tempUri, tempUrl,
videoId = getQueryString()["id"],
host = location.protocol + '//' + location.host,
baseUrl = "localhost",
str = "Visit W3Schools",
n = str.search(/w3schools/i),
x = 5,
y = 6,
z = x + y
/* End Variables */;
我们可以使用所有的方法,没有必要只选择其中一种。应用不同的方法可以使代码更易于阅读。
我将展示我Vue.js 3项目中的一个真实例子:
示例1
const [store, route] = [useStore(), useRoute()]
const
showAlert = computed(() => store.getters['utils/show']),
userIsLogged = computed(() => store.getters['auth/userIsLogged']),
albumTitle = computed(() => store.getters['albums/title']);
示例2
const
store = useStore(),
username = ref(''),
website = ref(''),
about = ref('');
const
isAppFirstRender = computed(() => store.getters['utils/isAppFirstRender']),
showToast = ref(false);
正如你在上面看到的,我们可以有一小块变量声明。没有必要声明大块。假设我有12个变量,我可以以一种有意义或看起来更容易阅读的方式将它们分组,而不需要冗长:
const
numberOne = 5,
numberTwo = 10,
numberThree = 15;
const
stringOne = 'asd',
stringTwo = 'asd2',
stringThree = 'asd3';
let [one, two, three] = [1,2,3]
当然,每个人都有自己的风格。这是我个人的偏好,混合使用所有方法。
我个人不喜欢冗长。我喜欢有它所需要的而不是更多的代码。
避免使用单语句版本(单var)的另一个原因是调试。如果在任何赋值行中抛出异常,堆栈跟踪只显示这一行。
如果使用逗号语法定义了10个变量,则无法直接知道哪个变量是罪魁祸首。
单个语句版本没有这种歧义。
我相信在我们开始使用ES6之前,使用单一的var声明的方法既不好也不好(如果你有lints和'use strict'的话)。这真的是一种口味偏好。但现在我的情况变了。以下是我对多行声明的一些看法:
Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations. ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.