大部分针对Javascript最合理的方法归纳。

发布时间:2026/7/4 2:59:25
大部分针对Javascript最合理的方法归纳。 原始类型我们可以直接使用值。ο stringο numberο booleanο nullο undefinedvar foo 1, bar foo; bar 9; console.log(foo, bar); // 1, 9• 复合类型我们通过引用对值进行间接访问。ο objectο arrayο functionvar foo [1, 2], bar foo; bar[0] 9; console.log(foo[0], bar[0]); // 9, 9Objects• 使用{}创建对象。// bad var item new Object(); // good var item {};• 不要使用保留字作为关键字。// bad var superman { class: superhero, default: { clark: kent }, private: true }; // good var superman { klass: superhero, defaults: { clark: kent }, hidden: true };Arrays• 使用[]创建数组// bad var items new Array(); // good var items [];• 如果你不知道数组长度使用Array#push。var someStack []; // bad someStack[someStack.length] abracadabra; // good someStack.push(abracadabra);• 当你需要复制数组的时候请使用Array#slice。var len items.length, itemsCopy [], i; // bad for (i 0; i len; i) { itemsCopy[i] items[i]; } // good itemsCopy items.slice();Strings• 对于字符串我们使用单引号。// bad var name Bob Parr; // good var name Bob Parr; // bad var fullName Bob this.lastName; // good var fullName Bob this.lastName;• 超过80个字符的字符串我们使用串联符号\让字符串多行显示。• 注意如果过度使用带串联符号的字符可能会影响到性能。// bad var errorMessage This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.; // bad var errorMessage This is a super long error that \ was thrown because of Batman. \ When you stop to think about \ how Batman had anything to do \ with this, you would get nowhere \ fast.; // good var errorMessage This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.;• 当我们在编程的时候需要拼接出一个字符串我们可以使用Array#join 代替字符串连接。尤其是对IE浏览器。var items, messages, length, i; messages [{ state: success, message: This one worked. },{ state: success, message: This one worked as well. },{ state: error, message: This one did not work. }]; length messages.length; // bad function inbox(messages) { items ul; for (i 0; i length; i) { items li messages[i].message /li; } return items /ul; } // good function inbox(messages) { items []; for (i 0; i length; i) { items[i] messages[i].message; } return ulli items.join(/lili) /li/ul; }Functions• 函数表达式// anonymous function expression var anonymous function() { return true; }; // named function expression var named function named() { return true; }; // immediately-invoked function expression (IIFE) (function() { console.log(Welcome to the Internet. Please follow me.); })();• 绝对不要在非函数块if,while申明一个函数。我们可以把函数申明变成一个函数表达式。// bad if (currentUser) { function test() { console.log(Nope.); } } // good if (currentUser) { var test function test() { console.log(Yup.); }; }