在第 4 行,它使用名為 map 的函式的第二個引數。但是實際上 transform(element) 所做的并沒有什么。也許我錯過了一些東西或者它參考了另一個函式。這個例子在 EloquentJavaScript 書第三版的第 5 章。
function map(array, transform) {
let mapped = [];
for (let element of array) {
mapped.push(transform(element));
}
return mapped;
}
let rtlScripts = SCRIPTS.filter(s => s.direction == "rtl");
console.log(map(rtlScripts, s => s.name));
// → ["Adlam", "Arabic", "Imperial Aramaic", …]
uj5u.com熱心網友回復:
transform是作為引數傳遞給map函式的函式。對于陣列的每個過濾物件,都將transform呼叫該物件,并回傳該物件的名稱值,并將其推入一個陣列(map迭代完成后從該陣列中回傳)。
箭頭函式語法可能有點混亂,所以這里是使用函式宣告的相同代碼。注意:此時您沒有呼叫它 - 您將它作為參考傳遞,以便以后可以呼叫它(in map)。
// Pass in the array of filtered objects, and the callback function
// which returns the name value of the obj in the current loop iteration
const out = map(rtlScripts, function (obj) {
return obj.name;
});
在此示例中,我將“元素”替換為“obj”,以便更容易理解正在操作的資料結構。
function map(array, transform) {
let mapped = [];
// For each object in the array call the
// transform function which returns only the name value
// and add that to the array
for (let obj of array) {
mapped.push(transform(obj));
}
return mapped;
}
const SCRIPTS = [{name: 'English',direction:'ltr'},{name:'Adlam',direction:'rtl'},{name: 'French',direction:'ltr'},{name:'Arabic',direction:'rtl'},{name:'Imperial Aramaic',direction:'rtl'}];
// `filter` out all the objects that are "rtl"
const rtlScripts = SCRIPTS.filter(obj => obj.direction == "rtl");
// Pass in the filtered array of objects, and for
// each of them call the function which returns only the name
const out = map(rtlScripts, function (obj) {
return obj.name;
});
console.log(out);
// → ["Adlam", "Arabic", "Imperial Aramaic", …]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442494.html
標籤:javascript 功能
