解构数组参数

问题描述 投票:0回答:1

我正在学习解构,并快速查询了如何引用数组的元素。

我正在使用以下方法破坏函数参数中对象内的嵌套数组:

function ajaxOptions({
    url,
    headers: [ 
        header0 ="Content-Type: text/plain",
        ...otherHeaders
    ] = [],
    data
} = {}) { 
    //... function body
}

这为第一个元素header0提供默认值,并扩展其他数组元素。

但是我实际上不能在任何参数中使用header0来引用此元素吗?我只需要将数组的第一个元素留空:headers: [, 'Header2', 'Header3']

例如:header: [, header0 = 'Header0', 'Header2', 'Header3']不会更改“ Content-Type”标头-因此该元素不是像对象属性(URL,数据等)那样的“命名元素”。标签header0的用途就像是为默认属性分配的占位符,对吗?

抱歉,如果我不清楚,我在下面提供了完整的代码,希望它更加清晰]

function ajaxOptions({
    url: url = "http://www.example.com",
    method: method = "post",
    headers: [ 
        header0 ="Content-Type: text/plain",
        ...otherHeaders
    ] = [],
    data: data,
    callback: callback 

} = {}) {
    return { url, method, headers: [header0, ...otherHeaders], data, callback};
}

function sayHello(){
    console.log('hello');
}


var defaults = ajaxOptions();

var settings = {
    url: 'http://someothersite.com', 
    data: 50, 
    callback: sayHello, 
    headers: [,  'Header2', 'Header3'] 
}

console.log(ajaxOptions(settings));

谢谢

javascript arrays destructuring
1个回答
0
投票

我认为您应该尝试使用对象来引用数组索引来解决您的问题。但是,如果您真正想要的是拥有一个返回函数内第一个值的数组,则可以尝试按以下方式排列数组。

const defaulHeader = ["Content-Type: text/plain"]
const otherHeaders = ["Some-type: application/json"]

 const headers = [ 
        ...defaulHeader,
        ...otherHeaders
    ]

console.log(headers)
© www.soinside.com 2019 - 2024. All rights reserved.