[英]inside Array.push without a function call
我想在將元素寫入數組之前執行更多邏輯:
tempDatensatz.push( () => {
var current = window.dataForDataTable[i].outbounds[key].updatedAt;
if (current) {
return current.toString();
} else {
return "".toString();
}
});
從該數組獲取值將通過以下方式實現:
tempDatensatz[0]()
但是我希望其中具有相同的邏輯而無需調用函數。 我需要一個普通的數組,在這里我得到一個像這樣的值:
tempDatensatz[0]
我該怎么辦?
更新后,我將我的項目發布到gitHub,如果需要更好的理解,可以看看:) https://github.com/te2020/GoEuro/blob/master/GoEuro/Views/Home/Index.cshtml
使用立即調用的函數,而不只是一個函數:
tempDatensatz.push( (function(){
var current = window.dataForDataTable[i].outbounds[key].updatedAt;
if (current) {
return current.toString();
} else {
return "".toString();
}
})());
該函數將在定義后立即執行,並返回結果。 因此push不會push
對該函數的引用,而是會推送其返回值(結果)。
您可以編寫代理,如下所示:
function makeProxy(array) { return new Proxy(array, { get(target, property) { return !isNaN(property) ? target[property]() : target[property]; } }); } const tempDatensatz = []; const useThisOne = makeProxy(tempDatensatz); useThisOne.push(() => alert("Hi, Jane!")); useThisOne[0];
推入/寫入數組將按預期工作,但檢索其元素將通過get
處理程序,該處理程序將執行該函數。
您可以只使用一個表達式,例如:
tempDatensatz.push(
(window.dataForDataTable[i].outbounds[key].updatedAt || '').toString();
);
對於更復雜的表達式,您通常可以使用三元運算符。 對於上面的內容,它看起來像這樣:
tempDatensatz.push(
window.dataForDataTable[i].outbounds[key].updatedAt
? window.dataForDataTable[i].outbounds[key].updatedAt.toString()
: ''
);
在查看鏈接到的github代碼時 ,您可以使用“ oneliner”來完成所有操作:
var tempDatensatz =
['companyId', 'mode', 'duration', 'outboundId', 'journeyId', 'departureTime',
'arrivalTime', 'stops', 'price', 'updatedAt', 'segments']
.map( prop => (window.dataForDataTable[i].outbounds[key][prop] || '').toString() );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.