JavaScript 是一種極為通用且功能強大的程式語言,廣泛用於 Web 開發。無論您是經驗豐富的開發人員還是新手,擁有一組方便的 JavaScript 程式碼片段都可以節省您的時間並簡化您的程式設計流程。在本文中,我編譯了 15 個簡短而精彩的 JavaScript 片段,涵蓋了各種任務。讓我們潛入吧!
const currentDateTime = new Date(); console.log(currentDateTime);
const number = [5, 2, 7, 10, 1] const maxNumber = Math.max(...number) // 10
function shuffleArray(array) { return array.sort(() => Math.random() - 0.5); }
const randomNumber = Math.floor(Math.random() * 10) + 1; console.log(randomNumber); // 7
const str = 'Hello, World!'' console.log(str.toLowerCase()); // hello, world!
const num = 5; if (num % 2 === 0) { console.log('Number is even'); } else { console.log('Number is odd'); } // 'Number is odd'
let seconds = 5; const countdown = setInterval(() => { console.log(seconds); seconds--; if (seconds < 0) { clearInterval(countdown); console.log('Countdown finished!'); } }, 1000); // 5 // 4 // 3 // 2 // 1 // Countdown finsihed!
const numbers = [1, 2, 3, 4, 5]; const strings = numbers.map(String); console.log(strings); // ['1', '2', '3', '4', '5']
let arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; const removeDuplicates = arr => [...new Set(arr)]; console.log(removeDuplicates(arr)); // ['apple', 'mango', 'orange']
const sentence = "This is a sentence"; const words = sentence.split(" "); console.log(words); // ['This', 'is', 'a', 'sentence']
function repeatString(str, n){ return str.repeat(n); } const repeatedStr = ('abc', 3); console.log(repeatedStr); // 'abcabcabc'
// Define the intersection function const intersection = (a, b) => a.filter(value => b.includes(value)); // Example arrays const arrayA = [1, 2, 3, 4, 5]; const arrayB = [4, 5, 6, 7, 8]; // Use the intersection function to find common elements const result = intersection(arrayA, arrayB); // Log the result to the console console.log(result); // [4, 5]
const name = 'Matin Imam'; const greeting = `Hello, ${name}!`; console.log(greeting); // "Hello, Matin Imam!"
const person = {name: 'Matin'}; const details = {work: 'Developer'}; const fullDetails = {...person, ...details}; console.log(fullDetails); // {name: 'Matin', age: 30}
setTimeout(() => location.href = https://www.linkedin.com/in/matin-imam/", 5000);
這 15 個 JavaScript 片段只是您透過幾行程式碼可以實現的目標的一瞥。無論您是操作數組、字串還是處理日期和時間,這些程式碼片段都可以幫助簡化您的開發過程。
如果您喜歡這篇文章並且想要聯繫,請隨時在 LinkedIn 上與我聯繫。我很樂意聯繫並分享更多有關軟體開發的見解!
在 LinkedIn 上與我聯絡
以上是簡短而有趣的 JavaScript 片段的詳細內容。更多資訊請關注PHP中文網其他相關文章!