javaScript中的一些简写,请备好!
废话不多说,直接列举一些JavaScript中的简写语法,仅供大家参考!
1、当我们确实有一个对象数组并且我们想要根据对象属性查找特定对象时,find方法确实很有用。
const data = [
{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//简写
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
2、如果仅在变量为 true 的情况下才调用函数,则可以使用 && 运算符。
//传统
if (test1) {
callMethod();
}
//简写
test1 && callMethod();
3.此函数有助于将对象转换为对象数组。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/

浙公网安备 33010602011771号