[英]How to add an element to an array only if a condition is fulfilled
有一個箭頭函數創建一個數組,如:
const myFunction = () => ["a", "b", "c"];
我想為其添加一個參數,如果該參數為true,則必須添加另一個元素。
像這兒:
const myFunction = (arg) => ["a", "b", "c", arg ? "d" : null];
此解決方案的問題是,如果arg !== true
,仍然會添加一個null元素,但在這種情況下我不希望添加任何內容。
您可以使用數組傳播。 根據arg
的值,一個空數組或包含d
的數組將散布到結果數組中:
const myFunction = (arg) => ["a", "b", "c", ...arg ? ['d'] : []]; console.log(JSON.stringify(myFunction(true))); // ["a","b","c","d"] console.log(JSON.stringify(myFunction())); // ["a","b","c"]
您可以使用concat
:
const myFunction = (arg) => ["a", "b", "c"].concat(arg ? ["d"] : []); console.log(myFunction(true)); console.log(myFunction(false));
您可以使用Array push() 。
const myFunction = (arg) => { const arr = ["a", "b", "c"]; if (arg) arr.push("d"); return arr; }; console.log(myFunction(true)); console.log(myFunction(false));
您可以將功能延長一點,
const myFunction = (arg) => { var tempArray = ["a", "b", "c"]; if (arg) { tempArray.push("d"); } return tempArray; }; console.log(myFunction(true) + ""); console.log(myFunction(false) + "");
const myFunction = (arg) => {
ret = ['a', 'b', 'c']
return arg === true ? ret.concat('d') : ret;
}
在其他解決方案中,您有arg ?
代替arg === true ?
。 如果您希望myFunction
僅對arg = true
返回帶有'd'
數組,那么您應該使用我的解決方案。 如果您希望它返回例如arg = 17
'd'
,但不希望它返回arg = 0
'd'
,請使用其他解決方案。
您也可以這樣做:
const myMethod = (arg) => {
var tempArray = ["item 1", "item 2", "item 3"];
!arg || tempArray.push("item 4");
return tempArray;
};
console.log(myMethod(false));
console.log(myMethod(true));
Ori有正確的答案 。 將其用於所有現代瀏覽器。 如果由於某種原因您仍然停留在舊版瀏覽器上-
["a", "b", "c"].concat(arg ? 'd' : [])
如果將數組存儲在變量中,則可以這樣進行:
const arr = ["a", "b", "c"]; const myFunction = arg => arg === true ? [...arr, "d"] : arr; console.log(myFunction(true)); console.log(myFunction());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.