如果三元是处理“if”验证的一种非常简单的方法:
代码:
function validateBetterCommunity(community) {
// Structure to Verify
return community === 'devto' ? 'You are right!' : 'You are wrong :(';
}
console.log(validateBetterCommunity('devto'));
// Expected output: "You're right!"
console.log(validateBetterCommunity('another one'));
// Expected output: "You're wrong :("
生成一个随机字符串 id 很简单:
// Structure to Generate
const randomIdentifier = Math.random().toString(30).slice(2.5);
console.log(randomIdentifier);
// Output: 'd5ptscfrln7';
检查是否有任何element
具有只读 activeElement
属性的焦点:
const onboarding = document.querySelector('.onboarding');
// Structure to Verify
const onboardingHasFocus = onboarding == document.activeElement;
console.log(onboardingHasFocus);
// Output: false;
通过spread(...)我们得到了“合并”元素的替代方法:
const devToPeople = [
{
name: 'Renan',
id: 'renancferro',
}
];
const newDevToParticipants = [
{
name: 'New User',
id: 'newUserId',
},
...devToPeople
];
console.log(newDevToParticipants);
// Output:
//[
// {
// name: 'New User',
// id: 'newUserId',
// },
// {
// "name": "Renan",
// "id": "renancferro"
// }
//];
用一行代码获取随机对象元素:
const newDevToParticipants = [
{
name: 'New User',
id: 'newUserId',
},
{
name: 'Renan',
id: 'renancferro',
},
];
// Structure to Get
const getRandomUser = (users) => users[Math.floor(Math.random() * users.length)];
console.log(getRandomUser(newDevToParticipants));
// Output: {
// "name": "Renan",
// "id": "renancferro"
//}
如何在对象数组中的特定位置插入新对象:
const newDevToParticipants = [
{
name: 'New User',
id: 'newUserId',
},
{
name: 'Renan',
id: 'renancferro',
},
];
// Structure to insert:
const insertNewUser = (originalArray, index, newItem) => [...originalArray.slice(0, index), newItem, ...originalArray.slice(index)];
const newUser = {
name: 'New User 2',
id: 'newUser2',
};
console.log(insertNewUser(newDevToParticipants, 1, newUser));
// Output
//[
// {
// "name": "New User",
// "id": "newUserId"
// },
// {
// "name": "New User 2",
// "id": "newUser2"
// },
// {
// "name": "Renan",
// "id": "renancferro"
// }
//]
将内容复制到剪贴板的基本且简单的结构:
const copyContentToClipboard = (contentToCopy) => navigator.clipboard.writeText(contentToCopy);
copyContentToClipboard('Do it different!');
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。