我试图将此deepMap([4,5, [3,4,[2]]], x => x + 5)
传递给此函数:
const deepMap = (arr, fn) => {
return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : fn), []);
}
之前它的工作原理如下:
const deepMap = (arr, fn) => {
return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second)] : second + 5), []);
}
但这并不允许我在第二个参数中使用该功能。我知道它需要像第二个例子一样工作,但我能想到改变它的唯一方法就像在第一个例子中一样。我通过实验尝试了很多变化,但我一直收到错误或错误答案。
答案 0 :(得分:1)
你应该放置函数的返回值而不是函数本身。像这样:
const deepMap = (arr, fn) => {
return arr.reduce((first, second) => first.concat(Array.isArray(second) ? [deepMap(second, fn)] : fn(second)), []);
}
答案 1 :(得分:0)
将数组和函数传递给递归//
// NSDecimalNumberBugTests.m
//
// Created by Lane Roathe on 6/1/17.
// For Quicken, Inc.
//
#import <XCTest/XCTest.h>
@interface NSDecimalNumberBugTests : XCTestCase
@end
@implementation NSDecimalNumberBugTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testBug {
// Use XCTAssert and related functions to verify your tests produce the correct results.
NSDecimalNumber* decimalLength;
NSUInteger interval;
// Start with a number that requires 65+ bits
// This FAILS (interval is zero)
decimalLength = [NSDecimalNumber decimalNumberWithString:@"1.8446744073709551616"];
interval = decimalLength.unsignedIntegerValue;
XCTAssert(interval == 1);
// This Works, interval is 1
interval = decimalLength.unsignedIntValue;
XCTAssert(interval == 1);
// Now test with a number that fits in 64 bits
// This WORKS (interval is 1)
decimalLength = [NSDecimalNumber decimalNumberWithString:@"1.8446744073709551615"];
interval = decimalLength.unsignedIntegerValue;
XCTAssert(interval == 1);
}
@end
调用并调用fn(cur)而不是仅指向它。
deepMap