簡體   English   中英

如果Array.prototype.map()沒有返回,它是否正確使用

[英]Is Array.prototype.map() being used properly if it does not return

.map()方法的典型用法是使用回調,該回調按順序傳遞數組中的每個元素,對該元素執行某些操作,然后為新數組返回相應的元素。 例如:

var arr = [1, 2, 3, 4, 5],
    arrMap = arr.map(function(element) {
        return element * 2;
    })

console.log(arrMap) // [2, 4, 6, 8, 10];

我發現在某些情況下,當試圖保持函數編碼風格並避免使用循環時,使用.map()方法而不必在回調中返回值會很有用。 一個使用.map將兩個數組轉換為對象的人為例子:

var arr1 = ['one', 'two', 'three', 'four', 'five'],
    arr2 = [1, 2, 3, 4, 5],
    obj = {},
    arr1.map(function(element, index) {
        obj[element] = arr2(index);
    });

我想知道的是,在沒有return語句的情況下使用Array.prototype.map是否存在技術上的錯誤。 這是以某種方式反對最佳實踐,還是使用.map代替使用此技術的循環或遞歸函數。

從技術上講, Array.prototype.map接受一個數組和一個函數,並返回另一個數組。 因此, map用於創建新數組。 在第二個示例中,您完全忽略了返回的數組。 你可以這樣檢查一下

    ...
    temp = arr1.map(function(element, index) {
        obj[element] = arr2[index];
    });

console.log(temp);

由於您沒有顯式返回任何內容,因此默認情況下JavaScript返回undefined temp會如此

[ undefined, undefined, undefined, undefined, undefined ]

這是不必要的。 因此,在這種情況下,您應該使用Array.prototype.forEach而不是map 這不會像map那樣創建數組。

var arr1 = ['one', 'two', 'three', 'four', 'five'],
    arr2 = [1, 2, 3, 4, 5],
    obj = {};
    arr1.forEach(function(element, index) {
        obj[element] = arr2[index];
    });
console.log(obj);

更好的是, 在這種情況下使用的最佳函數Array.prototype.reduce ,可以像這樣使用

var arr1 = ['one', 'two', 'three', 'four', 'five'],
    arr2 = [1, 2, 3, 4, 5],
    obj = arr1.reduce(function(result, currentElement, index) {
        result[currentElement] = arr2[index];
        return result;
    }, {});

console.log(obj);
// { one: 1, two: 2, three: 3, four: 4, five: 5 }

顧名思義, reduce會獲取一系列值並將其減少為單個值。 在這種情況下,我們對arr1使用reduce ,並在每次迭代時通過將當前鍵和值存儲在最終返回的result對象中來減少arr1

注意:由於您使用的是Node.js,您可以安裝函數式編程庫,如下划線或lodash,然后使用_.object完成此任務,就像這樣

var _ = require("underscore"),
    arr1 = ['one', 'two', 'three', 'four', 'five'],
    arr2 = [1, 2, 3, 4, 5];
console.log(_.object(arr1, arr2));
// { one: 1, two: 2, three: 3, four: 4, five: 5 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM