来一片成长快乐 —— JS Hacks 30+

简介: 童年回忆:小时候有个很出名的广告:“好高兴哦,又可以吃成长快乐了,我最爱吃成长快乐了~~”本篇带来 JavaScript 的常用特性 Hacks 之成长快乐!吃一片成长快乐,就好比吃了一片成长快乐╮(╯▽╰)╭

image.png


童年回忆:小时候有个很出名的广告:“好高兴哦,又可以吃成长快乐了,我最爱吃成长快乐了~~”


本篇带来 JavaScript 的常用特性 Hacks 之成长快乐!吃一片成长快乐,就好比吃了一片成长快乐╮(╯▽╰)╭


1. 用 length 调整数组大小



a=['Pune','Hyderabad','Banglore','Mumbai','Indore','Delhi']
console.log(a.length) //OUTPUT 6
a.length=3
console.log(a) //OUTPUT ['Pune','Hyderabad','Banglore']


2. 用数组解构赋值交换两个值



let a=10;
let b=20;
console.log(a,b) //OUTPUT: 10,20
[a,b]=[b,a]
console.log(a,b) //OUTPUT :20,10


3. 减少内存消耗的数组合并



//old way
a=[1,2,3,4,5]
b=[4,5,6,7,8]
c=a.concat(b) //This will Create a new array c and then will push contents fo array a and array b in array c which will consume lot of memory.
console.log(c) //OUTPUT:1,2,3,4,5,4,5,6,7,8
//new way
a=[1,2,3,4,5]
b=[4,5,6,7,8]
a.push.apply(a,b) // it will only push the content of array b in array a.
console.log(a)


4. 用 Boolean 过滤 null/undefined



a=[null,undefined,{"name":"Alex"},{"name":"Nick"},{"name":""},null]
c=a.filter(item=>item.name.length>0) //this will show error Uncaught TypeError: Cannot read property 'length' of undefined
// we can use filter with Boolean to remove null and undefined Values
c=a.filter(Boolean).filter(it=>it.name.length>0) //This will work
console.log(c) //OUTPUT


5. 扩展运算遍历从 0 到 n



[...Array(100)].map((it,index)=>console.log(index))


6. 正则 /g 替换所有



str="India India USA India UK India"
console.log(str.replace(/India/,'USA'))
//OUPUT USA India USA India UK India
//Add g at the end of string it will replace all occurences
console.log(str.replace(/India/g,'USA'))


7. 善用“或且非”



// old way
let a="hello"
let b;
if(a==undefined){
    b="Nothing"
}
else{
    b=a
}
console.log(b) //hello
// new way
b=a||"Nothing"
console.log(b) //hello
// old way
let data={"name":"Allen"}
if(data!=undefined)console.log(data.name)
// new way
data!=undefined&&console.log(data.name)


8. 字符串数字互转



// string to number
a="123"
console.log(+a) //Output 123
b=""
console.log(+b) //NaN
//number to string
a=123
console.log(a+"")


9. console 中的占位符



// %s replaces an element with a string
console.log("Helllo I love %s so much","Javascript")
// %d  replaces an element with an integer
console.log("Helllo %d ",1)
// %f  replaces an element with a float
console.log("Helllo  %f ",1.078)
// %(o|O) | element is displayed as an object.
console.log("Helllo %O",{"Name":"Sidd"})
// %c | Applies the provided CSS
console.log("%cThis is a red text", "color:red");


10. console.table



// we can use console.table to show objects in tabular format
a=[{"city":"Banglore"},{"city":"Pune"},{"city":"Mumbai"}]
console.table(a)

image.png


11. 截取数组最后几位



a=[1,2,3,4,5,6,7,8,9,10]
conosle.log(a.slice(-1))//[10]
console.log(a.slice(-2))//[9,10]


12. js 求幂



console.log(2 ** 3) //8
console.log(2 ** 12)  //4096


13. 用“!!”鉴真



//In javascript following values are falsy  0, "", null, undefined, NaN and of course false except it all are truly
// use !! operator to get falsy or trult
console.log(!!0,!! "",!!null,!! "Hii",!! undefined,!! NaN ,!! false,!! true)
//OUTPUT false false false true false false false true


14. 用“eval”来调用函数



const print=()=>console.log("hello")
setTimeout(()=>eval('print')(),1000)//hello


15. typeof 判断类型



//The typeof operator returns a string indicating the type of the unevaluated operand.
console.log(typeof 12) //number
console.log(typeof "hello") //string
console.log(typeof []) //object
console.log(typeof true) //boolean
console.log(typeof {}) //object


16. yield 关键字暂停函数



//The yield keyword is used to pause and resume a generator function 
function* list(index,length) {
  while (index < length) {
    yield index;
    index++;
  }
}
const iterator = list(0,10);
console.log(iterator.next().value);
// expected output: 0
console.log(iterator.next().value);
// expected output: 1


17. JS 中的 function*



//The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
function* generator(i) {
  yield i;
  yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value);
// expected output: 10
console.log(gen.next().value);
// expected output: 20


18. JS 中的 new.target



// new.target is used to detect that weather a function or constructor call using new or not.
// if it called using new it will return refrence to constructor or function else it return undefined.
function learn(){ 
  new.target?console.log("Called using new"):console.log("Called without new")
}
learn() //called without learn
new learn() //called using new.
//In arrow functions, new.target is inherited from the surrounding scope.


19. 表达式标签



//The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.
loop1:
for (let i = 0; i < 5; i++) {
  loop2:
  for(let j=0;j<5;j++)
  {
    console.log(i,j)
    if(i==j)
    {
      continue loop1
    }
  }
}
// 0 0
// 1 0
// 1 1
// 2 0
// 2 1
// 2 2
// 3 0
// 3 1
// 3 2
// 3 3
// 4 0
// 4 1
// 4 2
// 4 3
// 4 4


20. 剩余参数



//The rest parameter syntax allows a function to accept an indefinite number of arguments as an array,it like variadic function in C.
function abc(...args)
{
  console.log(args)
}
abc(1) //[1]
abc(1,2) //[1,2]
abc(1,2,3) //[1,2,3]
abc(1,2,3,4)//[1,2,3,4]


21. slice VS splice



slice 不影响原始数组;

splice 用于对原始数组进行更改,要么删除某些元素,要么替换它们;


//slice
//array.slice(start,end)
// start: denotes the starting index of slicing.
// end: denotes the end index of slicing
A=[1,2,3,4,5,6,7,8,9,10]
B=A.slice(2,5)
console.log(A)
//[1,2,3,4,5,6,7,8,9,10] 
console.log(B)
// [3,4,5]  
//splice
//array.splice(start,deleteCount,n1,n2,n3,...)
// start:  the starting index of splicing.
// deleteCount: number of elements to delete from start index.
// n1,n2,n3,n4....: these elements will be added after start index.
A=[1,2,3,4,5,6,7,8,9,10]
B=A.splice(2,3)
console.log(A)
//[1,2,6,7,8,9,10] 
console.log(B)
// [3,4,5]  
C=A.splice(0,2,10,11,12,13,14)
console.log(C)
//[1,2]
console.log(A)
//[10,11,12,13,14,6,7,8,9,10]


22. forEach VS map



forEach 通常用于在迭代过程中不需要返回某些内容;


map 则需要返回(避免在任何地方都使用 map);

//map
A=[1,2,3,4,5,6,7,8,9,10]
B=A.map(item=>item%2==0)
console.log(B)
//[ false, true, false, true, false, true, false, true, false, true ]
//[]
//forEach
A=[1,2,3,4,5,6,7,8,9,10]
C=A.forEach(item=>item%2==0)
console.log(C)
//undefined


23. 用“in”判断存在



a=[1,2,4,5,7,8]
console.log(2 in a)
//true
console.log(9 in a)
//false


24. Getters & Setters



使用 js 原生 Getters & Setters;

A={
    subjectName:"Math",
    set marks(value)
    {
    if(isNaN(value))throw Error("Marks must be number")
    //for propert name you have to use _(underscore) before its name.
    else this._marks=value 
    },
    get result()
    {
    if(this._marks>=33)return "Pass" 
    else return "Fail"
    }
}
A.marks=59
console.log(A.result)
//Pass
A.marks='sa'
//Will throw Error


25. 遍历对象



//declaration of JSON
a={"firstName":"Siddhant","lastName":"Johari","age":"XX","phoneNumber":"+9187XXXXXXXX"}
Object.keys(a).forEach(it=>console.log(it,":",a[it]))//Object.keys(a) it will create an array with keys of a
// firstName : Siddhant
// lastName : Johari
// age : XX
// phoneNumber : +9187XXXXXXXX


26. 多个“或”判断



// old way
if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana' || fruit ==='grapes') {
    //code
}
// new way
if (['apple', 'orange', 'banana', 'grapes'].includes(fruit)) {
   //code
}


27. 多个“且”判断



// old way
if(obj && obj.address && obj.address.postalCode) {
    console.log(obj.address.postalCode)
}
// new way
console.log(obj?.address?.postalCode); // 可选链操作符,ES2020 必会


28. switch case 变形



// old way
switch (number) {
  case 1:
     return 'one';
  case 2:
     return 'two';
  default:
     return;
}
// new way
const data = {
  1: 'one',
  2: 'two'
};
//Access it using
data[num]


29. 条件调用



// old way
function area() {
    console.log('area');
}
function volume() {
    console.log('volume');
}
if(type === 'square') {
    area();
} else {
    volume();
}
// new way
(type === 'square' ? area : volume)()


30. 数组深拷贝



// old way
const newArr = JSON.parse(JSON.stringify(arr))
// new way
const newArr = slice(arr)

以上。总有一个你不知道的吧?

告诉你一个小秘密,本篇 评论抽奖 ╰(°▽°)╯

学习了第几点,评论扣个 “第 n 点,学习了”,全都知道的,评论扣个 “就这?”......

我是掘金安东尼,公众号【掘金安东尼】,输出暴露输入,技术洞见生活!再会~


相关文章
|
2月前
|
JavaScript iOS开发
js常用的代码有哪些 老司机带你来看看
js常用的一些代码分享给大家
21 4
|
JavaScript
学习JS第六天
学习JS第六天
63 0
|
JavaScript
学习JS第九天
学习JS第九天
113 0
|
JavaScript
学习JS第七天
学习JS第七天
64 0
|
JavaScript
学习JS第五天
学习JS第五天
45 0
|
JavaScript 数据安全/隐私保护
学习JS第四天
学习JS第四天
70 0
|
JavaScript
学习JS第三天
学习JS第三天
58 0
|
JavaScript
学习JS第八天
学习JS第八天
49 0
|
JavaScript
JS查漏补缺——神奇的this
JS查漏补缺系列是我在学习JS高级语法时做的笔记,通过实践费曼学习法进一步加深自己对其的理解,也希望别人能通过我的笔记能学习到相关的知识点。这一次我们来理解一下面试题常考的this的指向
115 0
|
JSON JavaScript API