gpt4 book ai didi

javascript - 我应该将变量放在 if 条件中吗?

转载 作者:行者123 更新时间:2023-12-05 01:22:11 24 4
gpt4 key购买 nike

我想知道,根据良好做法,在这种情况下放置变量最方便的方法是什么:

如果你有一个函数,只有当条件语句为真时它的内容才会被执行,你会把变量放在哪里?

  addMessage (text) {
let lastMessage = React.findDOMNode(this.refs.messages);
if (text.length) {
ChatActions.addMessage(text);
lastMessage.scrollTop = lastMessage.scrollHeight;
}
}

或者像这样:

  addMessage (text) {
if (text.length) {
let lastMessage = React.findDOMNode(this.refs.messages);
ChatActions.addMessage(text);
lastMessage.scrollTop = lastMessage.scrollHeight;
}
}

最佳答案

是的,绝对是

正如许多 JavaScript 风格指南中所述:


Airbnb JavaScript Style Guide() {

13.4 Assign variables where you need them, but place them in a reasonable place.
Why? let and const are block scoped and not function scoped.

Principles of Writing Consistent, Idiomatic JavaScript

// 2.B.1.4
// const and let, from ECMAScript 6, should likewise be at the top of their scope (block).

// Bad
function foo() {
let foo,
bar;
if ( condition ) {
bar = "";
// statements
}
}
// Good
function foo() {
let foo;
if ( condition ) {
let bar = "";
// statements
}
}

关于javascript - 我应该将变量放在 if 条件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061509/

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