js如何破坏函数的默认值?

时间:2018-11-02 08:59:40

标签: javascript ecmascript-6

我有此代码:

function houseDescriptor([houseColor = 'green', shutterColors = ['red']] = []) {
    console.log(houseColor, shutterColors);
}

houseDescriptor('nbh');

为什么控制台打印:n b

它如何工作?

为什么如果我传递字符串没有错误,但是如果我使用houseDescriptor(123),则会出现错误?

2 个答案:

答案 0 :(得分:1)

字符串被视为可迭代,数字则不被视为。它正在对字符串进行基于索引的解构,这就是为什么只打印n和b的原因。

Have a look at listed iterables

答案 1 :(得分:1)

function houseDescriptor([houseColor = 'green', shutterColors = ['red']] = []) 

上面的函数接受一个类型为array的参数。因此,当您将“ nbh”作为参数传递时,它将被视为可迭代并对其进行破坏。

上面的代码等同于

let [firstCharacter, secondCharacter] = 'Stack'; 
console.log(`firstCharacter: ${firstCharacter} , secondCharacter: ${secondCharacter}`)