在JS中以编程方式分解数组

时间:2019-06-04 09:21:45

标签: javascript arrays ecmascript-6 destructuring

我感觉这是不可能的,但是也许有一个晦涩的技巧可以使我学会以下操作:

let picker = FilePicker(mode: .document, viewController: vc)
    picker.pick(fileExists: false, source: .view(vc.view, vc.view.bounds)) { _, result in
        if case .document(let url) = result {
            do {
                var isDir: ObjCBool = false
                if !FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) {
                    throw AppError.other("file does not exist")
                }
                if isDir.boolValue {
                    return
                }
                if url.lastPathComponent.hasSuffix("svg"), let image = SVGKImage(contentsOf: url), let imgView = SVGKFastImageView(svgkImage: image) {

                    UIView.animate(withDuration: 1.0, animations: {
                        vc.view.addSubview(imgView)
                        imgView.addConstraintsToMatchSuperview()
                    }, completion: { (done) in
                        let layer = CALayer()
                        layer.contents = imgView.image.uiImage.cgImage
                        vc.addLayer(layer: layer)
                        imgView.removeFromSuperview()
                    })

                }
            } catch {
                // stuff
            }
        }
    }

换句话说,用来自数组的名称初始化变量。在上面,变量“ num1”将被赋值为1337。

用例是:x和y的长度将始终相同;他们的订单将永远匹配;我们无法预测两者的内容。当然,我可以简单地在x上// pseudocode let x = ["num1", "str1"] let y = [1337, "foo"] let [x...] = y // desired results => num1 === 1337 str1 === "foo" ,并将位置与y中的内容匹配,但是我想看看我是否可以更具声明性并以编程方式匹配它们。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您可以将输出作为对象,如下所示:

let x = ["number", "string"];
let y = [1337, "foo"];
const res = x.reduce((acc, curr, idx) => ({ ...acc, [curr]: y[idx] }), {});
console.log(res);

或者如果您想使用二维数组:

let x = ["number", "string"];
let y = [1337, "foo"];
const res = x.map((e, i) => [e, y[i]]);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }