梦唐 發表於 2021-8-16 17:00:00

10 个超棒的 JavaScript 简写技巧

<p>今天我要分享的是10个超棒的JavaScript简写方法,可以加快开发速度,让你的开发工作事半功倍哦。</p>
<p>开始吧!</p>
<h2 id="1-合并数组">1. 合并数组</h2>
<p><strong>普通写法:</strong></p>
<p>我们通常使用<code>Array</code>中的<code>concat()</code>方法合并两个数组。用<code>concat()</code>方法来合并两个或多个数组,不会更改现有的数组,而是返回一个新的数组。请看一个简单的例子:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);

console.log( fruits );
//=&gt; ["🍉", "🍊", "🍇", "🍎", "🍏"]
</code></pre>
<p><strong>简写方法:</strong></p>
<p>我们可以通过使用ES6扩展运算符(<code>...</code>)来减少代码,如下所示:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];// &lt;-- here

console.log( fruits );
//=&gt; ["🍉", "🍊", "🍇", "🍎", "🍏"]
</code></pre>
<p>得到的输出与普通写法相同。</p>
<h2 id="2-合并数组在开头位置">2. 合并数组(在开头位置)</h2>
<p><strong>普通写法:</strong></p>
<p>假设我们想将<code>apples</code>数组中的所有项添加到<code>Fruits</code>数组的开头,而不是像上一个示例中那样放在末尾。我们可以使用<code>Array.prototype.unshift()</code>来做到这一点:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];

// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)

console.log( fruits );
//=&gt; ["🍎", "🍏", "🥭", "🍌", "🍒"]
</code></pre>
<p>现在红苹果和绿苹果会在开头位置合并而不是末尾。</p>
<p><strong>简写方法:</strong></p>
<p>我们依然可以使用ES6扩展运算符(<code>...</code>)缩短这段长代码,如下所示:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒'];// &lt;-- here

console.log( fruits );
//=&gt; ["🍎", "🍏", "🥭", "🍌", "🍒"]
</code></pre>
<h2 id="3-克隆数组">3. 克隆数组</h2>
<p><strong>普通写法:</strong></p>
<p>我们可以使用<code>Array</code>中的<code>slice()</code>方法轻松克隆数组,如下所示:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=&gt; ["🍉", "🍊", "🍇", "🍎"]
</code></pre>
<p><strong>简写方法:</strong></p>
<p>我们可以使用ES6扩展运算符(<code>...</code>)像这样克隆一个数组:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits];// &lt;-- here

console.log( cloneFruits );
//=&gt; ["🍉", "🍊", "🍇", "🍎"]
</code></pre>
<h2 id="4-解构赋值">4. 解构赋值</h2>
<p><strong>普通写法:</strong></p>
<p>在处理数组时,我们有时需要将数组“解包”成一堆变量,如下所示:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let redApple = apples;
let greenApple = apples;

console.log( redApple );    //=&gt; 🍎
console.log( greenApple );//=&gt; 🍏
</code></pre>
<p><strong>简写方法:</strong></p>
<p>我们可以通过解构赋值用一行代码实现相同的结果:</p>
<pre><code class="language-javascript">let apples = ['🍎', '🍏'];
let = apples;// &lt;-- here

console.log( redApple );    //=&gt; 🍎
console.log( greenApple );//=&gt; 🍏
</code></pre>
<h2 id="5-模板字面量">5. 模板字面量</h2>
<p><strong>普通写法:</strong></p>
<p>通常,当我们必须向字符串添加表达式时,我们会这样做:</p>
<pre><code class="language-javascript">// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=&gt; Hello, Palash!

// Add &amp; Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=&gt; Sum = 30 and Subtract = 10
</code></pre>
<p><strong>简写方法:</strong></p>
<p>通过模板字面量,我们可以使用反引号(<code>),这样我们就可以将表达式包装在</code>${...}`中,然后嵌入到字符串,如下所示:</p>
<pre><code class="language-javascript">// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`);// &lt;-- No need to use + var + anymore
//=&gt; Hello, Palash!

// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=&gt; Sum = 30 and Subtract = 10
</code></pre>
<h2 id="6-for循环">6. For循环</h2>
<p><strong>普通写法:</strong></p>
<p>我们可以使用<code>for</code>循环像这样循环遍历一个数组:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Loop through each fruit
for (let index = 0; index &lt; fruits.length; index++) {
console.log( fruits );// &lt;-- get the fruit at current index
}

//=&gt; 🍉
//=&gt; 🍊
//=&gt; 🍇
//=&gt; 🍎
</code></pre>
<p><strong>简写方法:</strong></p>
<p>我们可以使用<code>for...of</code>语句实现相同的结果,而代码要少得多,如下所示:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using for...of statement
for (let fruit of fruits) {
console.log( fruit );
}

//=&gt; 🍉
//=&gt; 🍊
//=&gt; 🍇
//=&gt; 🍎
</code></pre>
<h2 id="7-箭头函数">7. 箭头函数</h2>
<p><strong>普通写法:</strong></p>
<p>要遍历数组,我们还可以使用<code>Array</code>中的<code>forEach()</code>方法。但是需要写很多代码,虽然比最常见的<code>for</code>循环要少,但仍然比<code>for...of</code>语句多一点:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using forEach method
fruits.forEach(function(fruit){
console.log( fruit );
});

//=&gt; 🍉
//=&gt; 🍊
//=&gt; 🍇
//=&gt; 🍎
</code></pre>
<p><strong>简写方法:</strong></p>
<p>但是使用箭头函数表达式,允许我们用一行编写完整的循环代码,如下所示:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit =&gt; console.log( fruit ));// &lt;-- Magic ✨

//=&gt; 🍉
//=&gt; 🍊
//=&gt; 🍇
//=&gt; 🍎
</code></pre>
<p>大多数时候我使用的是带箭头函数的<code>forEach</code>循环,这里我把<code>for...of</code>语句和<code>forEach</code>循环都展示出来,方便大家根据自己的喜好使用代码。</p>
<h2 id="8-在数组中查找对象">8. 在数组中查找对象</h2>
<p><strong>普通写法:</strong></p>
<p>要通过其中一个属性从对象数组中查找对象的话,我们通常使用<code>for</code>循环:</p>
<pre><code class="language-javascript">let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
for (let index = 0; index &lt; arr.length; index++) {

    // Check the value of this object property `name` is same as 'Apples'
    if (arr.name === 'Apples') {//=&gt; 🍎

      // A match was found, return this object
      return arr;
    }
}
}

let result = getApples(inventory);
console.log( result )
//=&gt; { name: "Apples", quantity: 10 }
</code></pre>
<p><strong>简写方法:</strong></p>
<p>哇!上面我们写了这么多代码来实现这个逻辑。但是使用<code>Array</code>中的<code>find()</code>方法和箭头函数<code>=&gt;</code>,允许我们像这样一行搞定:</p>
<pre><code class="language-javascript">// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
return arr.find(obj =&gt; obj.name === 'Apples');// &lt;-- here
}

let result = getApples(inventory);
console.log( result )
//=&gt; { name: "Apples", quantity: 10 }
</code></pre>
<h2 id="9-将字符串转换为整数">9. 将字符串转换为整数</h2>
<p><strong>普通写法:</strong></p>
<p><code>parseInt()</code>函数用于解析字符串并返回整数:</p>
<pre><code class="language-javascript">let num = parseInt("10")

console.log( num )         //=&gt; 10
console.log( typeof num )//=&gt; "number"
</code></pre>
<p><strong>简写方法:</strong></p>
<p>我们可以通过在字符串前添加<code>+</code>前缀来实现相同的结果,如下所示:</p>
<pre><code class="language-javascript">let num = +"10";

console.log( num )         //=&gt; 10
console.log( typeof num )    //=&gt; "number"
console.log( +"10" === 10 )//=&gt; true
</code></pre>
<h2 id="10-短路求值">10. 短路求值</h2>
<p><strong>普通写法:</strong></p>
<p>如果我们必须根据另一个值来设置一个值不是falsy值,一般会使用<code>if-else</code>语句,就像这样:</p>
<pre><code class="language-javascript">function getUserRole(role) {
let userRole;

// If role is not falsy value
// set `userRole` as passed `role` value
if (role) {
    userRole = role;
} else {

    // else set the `userRole` as USER
    userRole = 'USER';
}

return userRole;
}

console.log( getUserRole() )         //=&gt; "USER"
console.log( getUserRole('ADMIN') )//=&gt; "ADMIN"
</code></pre>
<p><strong>简写方法:</strong></p>
<p>但是使用短路求值(<code>||</code>),我们可以用一行代码执行此操作,如下所示:</p>
<pre><code class="language-javascript">function getUserRole(role) {
return role || 'USER';// &lt;-- here
}

console.log( getUserRole() )         //=&gt; "USER"
console.log( getUserRole('ADMIN') )//=&gt; "ADMIN"
</code></pre>
<p>基本上,<code>expression1 || expression2</code>被评估为<code>真</code>表达式。因此,这就意味着如果第一部分为真,则不必费心求值表达式的其余部分。</p>
<h2 id="补充几点">补充几点</h2>
<p><strong>箭头函数</strong></p>
<p>如果你不需要<code>this</code>上下文,则在使用箭头函数时代码还可以更短:</p>
<pre><code class="language-javascript">let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);
</code></pre>
<p><strong>在数组中查找对象</strong></p>
<p>你可以使用对象解构和箭头函数使代码更精简:</p>
<pre><code class="language-javascript">// Get the object with the name `Apples` inside the array
const getApples = array =&gt; array.find(({ name }) =&gt; name === "Apples");

let result = getApples(inventory);
console.log(result);
//=&gt; { name: "Apples", quantity: 10 }
</code></pre>
<p><strong>短路求值替代方案</strong></p>
<pre><code class="language-javascript">const getUserRole1 = (role = "USER") =&gt; role;
const getUserRole2 = role =&gt; role ?? "USER";
const getUserRole3 = role =&gt; role ? role : "USER";
</code></pre>
<p>最后,我想借用一段话来作结尾:</p>
<blockquote>
<p>代码之所以是我们的敌人,是因为我们中的许多程序员写了很多很多的狗屎代码。如果我们没有办法摆脱,那么最好尽全力保持代码简洁。</p>
<p>如果你喜欢写代码——真的,真的很喜欢写代码——你代码写得越少,说明你的爱意越深。</p>
</blockquote>
<p>欢迎关注我的公众号:前端新世界<br>
只关注前端技术,每日分享 JS / CSS 技术教程;Vue、React、jQuery等前端开发组件</p>
<p><img src="https://img2020.cnblogs.com/blog/352752/202108/352752-20210816164635077-1246528230.png"></p><br><br>
来源:https://www.cnblogs.com/frontworld/p/15148751.html
頁: [1]
查看完整版本: 10 个超棒的 JavaScript 简写技巧