卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章67267本站已运行429

简短而有趣的 JavaScript 片段

简短而有趣的 javascript 片段

javascript 是一种极其通用且功能强大的编程语言,广泛用于 web 开发。无论您是经验丰富的开发人员还是新手,拥有一组方便的 javascript 代码片段都可以节省您的时间并简化您的编码过程。在本文中,我编译了 15 个简短而精彩的 javascript 片段,涵盖了各种任务。让我们潜入吧!

01.获取当前数据和时间

const currentdatetime = new date();
console.log(currentdatetime);

02. 查找数组中的最大数

const number = [5, 2, 7, 10, 1]
const maxnumber = math.max(...number)

// 10

03. 随机排列数组

function shufflearray(array) {
    return array.sort(() => math.random() - 0.5);
}

04.生成1到10之间的随机数

const randomnumber = math.floor(math.random() * 10) + 1;
console.log(randomnumber);

// 7

05. 将字符串转换为小写

const str = 'hello, world!''
console.log(str.tolowercase());

// hello, world!

06. 检查是偶数还是奇数

const num = 5;
if (num % 2 === 0) {
    console.log('number is even');
} else {
    console.log('number is odd');
}

// 'number is odd'

07. 创建一个简单的 10 秒倒计时器

let seconds = 5;
const countdown = setinterval(() => {
    console.log(seconds);
    seconds--;
    if (seconds 



<h2>
  
  
  08. 将数字数组转换为<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/52359.html" target="_blank">字符串数组</a>
</h2>



<pre class="brush:php;toolbar:false">const numbers = [1, 2, 3, 4, 5];
const strings = numbers.map(string);
console.log(strings);

// ['1', '2', '3', '4', '5']

09.删除重复项

let arr = ["apple", "mango", "apple", "orange", "mango", "mango"];
const removeduplicates = arr =&gt; [...new set(arr)];

console.log(removeduplicates(arr));

// ['apple', 'mango', 'orange']

10. 将句子转换为单词数组

const sentence = "this is a sentence";
const words = sentence.split(" ");

console.log(words);

// ['this', 'is', 'a', 'sentence']

11. 重复字符串

function repeatstring(str, n){
    return str.repeat(n);
}

const repeatedstr = ('abc', 3);
console.log(repeatedstr);

// 'abcabcabc'

12. 求数组的交集

// define the intersection function
const intersection = (a, b) =&gt; a.filter(value =&gt; 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]

13. 创建动态字符串

const name = 'matin imam';
const greeting = `hello, ${name}!`;
console.log(greeting); // "hello, matin imam!"

14. 合并对象

const person = {name: 'matin'};
const details = {work: 'developer'};

const fulldetails = {...person, ...details};
console.log(fulldetails);

// {name: 'matin', age: 30}

15.延迟后重定向到新的url

setTimeout(() =&gt; location.href = https://www.linkedin.com/in/matin-imam/", 5000);

这 15 个 javascript 片段只是您通过几行代码可以实现的功能的一瞥​​。无论您是操作数组、字符串还是处理日期和时间,这些代码片段都可以帮助简化您的开发过程。


与我联系

如果您喜欢这篇文章并且想要联系,请随时在 linkedin 上与我联系。我很乐意联系并分享更多有关软件开发的见解!

在 linkedin 上与我联系

立即学习“Java免费学习笔记(深入)”;

卓越飞翔博客
上一篇: 创建具有动态背景动画的时尚博客卡
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏