新聞中心
我們每個 JavaScript 程序員都應(yīng)該學習使用 JavaScript 單行代碼技巧來提高生產(chǎn)力,因此,今天這篇文章,我們將分享一些可以在日常開發(fā)生活中使用的單行代碼技巧。

成都創(chuàng)新互聯(lián)成立于2013年,先為德欽等服務(wù)建站,德欽等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為德欽企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
其實,關(guān)于JavaScript的單行代碼技巧,我們在前面的文章也分享了很多,如果已經(jīng)會了的小伙伴,就當是復習;如果還不知道或者不是很了解的話,就當新內(nèi)容來學習,收藏好,留著備用。
并且在今天文章的推薦閱讀區(qū)域里,我會把之前分享的JavaScript的單行代碼技巧的文章鏈接一并附上,方便大家查閱學習。
這些內(nèi)容里可能有一些重疊的知識,不過沒有關(guān)系,我們多看看幾次,加深印象,就好像我們的一些模糊朋友一樣,可能對對方的容貌不是很清晰,但是多見幾次面,我們就記住對方了,學習技術(shù)也是這樣,一邊看一邊用,自然就記住了。
好了,我們現(xiàn)在開始今天的內(nèi)容吧。
1. 對數(shù)組進行排序
使用 sort 方法對數(shù)組進行排序非常簡單。
const number = [2,6,3,7,8,4,0];
number.sort();
// expected output: [0,2,3,4,6,7,8]
2.檢查數(shù)組中的值
很多時候我們需要檢查值是否存在于數(shù)組中,借助 include 方法。
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
3.過濾數(shù)組
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
4. 從數(shù)組中查找元素
如果我們只需要一個元素,但數(shù)組中有很多元素,不要擔心 JavaScript 有 find 方法。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
5. 查找數(shù)組中任何元素的索引
要查找數(shù)組中元素的索引,可以簡單地使用 indexOf 方法。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
6. 將數(shù)組轉(zhuǎn)換為字符串
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join(", "));
// expected output: "Fire, Air, Water"
7.查找號碼是偶數(shù)還是奇數(shù)
很容易找出給定的數(shù)字是偶數(shù)還是奇數(shù)
const isEven = num => num % 2 === 0;
or
const isEven = num => !(n & 1);
8.刪除數(shù)組中的所有重復值
刪除數(shù)組中所有重復值的一種非常簡單的方法
const setArray = arr => [...new Set(arr)];
const arr = [1,2,3,4,5,1,3,4,5,2,6];
setArray(arr);
// expected output: [1,2,3,4,5,6]
9. 合并多個數(shù)組的不同方式
// merge but don't remove duplications
const merge = (a, b) => a.concat(b);
or
const merge = (a, b) => [...a, ...b];
// merge with remove duplications
const merge = (a, b) => [...new Set(a.concat(b))];
or
const merge = (a, b) => [...new Set([...a, ...b])];
10. 滾動到頁面頂部
有很多方法可以將頁面滾動到頂部。
const goToTop = () => window.scrollTo(0,0, "smooth");
or
const scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});
// scroll to bottom of the page
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
11.復制到剪貼板
在 Web 應(yīng)用程序中,復制到剪貼板因其對用戶的便利性而迅速普及。
const copyToClipboard = text (navigator.clipboard?.writeText ?? Promise.reject)(text);
總結(jié)
以上就是我今天跟你分享的11個關(guān)于JavaScript的單行代碼技巧,如果你覺得有用的話,請記得點贊我,關(guān)注我,如果你還想查看學習更多關(guān)于單行代碼技巧知識,請點擊推薦閱讀里的文章內(nèi)容。
當前標題:11個JavaScript單行代碼技巧
網(wǎng)頁地址:http://www.dlmjj.cn/article/dhepojo.html


咨詢
建站咨詢
