我有一个功能,你可以看到以下:
我想要参数use_five
:
function put_list(use_five) {
if (use_five) {
return [{name:"a"}, {name: "asxsa"}, {name: "ABC"}, {name: "Well"}, {name: "5"}]
}else {
return [{name:"a"}, {name: "asxsa"}, {name: "ABC"}, {name: "Well"}]
}
}
如果是true
,我会回复:
[{name:"a"}, {name: "asxsa"}, {name: "ABC"}, {name: "Well"}, {name: "5"}]
如果是false
,我会回复:
[{name:"a"}, {name: "asxsa"}, {name: "ABC"}, {name: "Well"}]
我知道我可以使用if-else进行判断,但我不想这样做,因为在我的实际项目中,列表中有很多项目。
那么,有没有办法通过一行实现它而不是写两行列表?
答案 0 :(得分:1)
function put_list(use_five) {
let result = [{name:"1"}, {name: "2"}, {name: "3"}, {name: "4"}];
if (use_five) {
result.push({name:"5"});
}
return result;
}
答案 1 :(得分:1)
我无法开始猜测你的真实情况,但这是减少重复的一种方法:
function put_list(use_five) {
var items = [{name:"a"}, {name: "asxsa"}, {name: "ABC"}, {name: "Well"}];
if (use_five) {
items.push({name: "5"});
}
return items;
}
答案 2 :(得分:0)
您可以将数组切片以获得所需的元素数。
function getList(take5) {
var data = [{ name: "1" }, { name: "2" }, { name: "3" }, { name: "4" }, { name: "5" }];
return data.slice(0, take5 ? 5 : 4);
}
console.log(getList());
console.log(getList(true));