[英]Array destructuring in function parameters
我在這里有一些與數組解構有關的東西我還不完全理解。
在以下示例中:
function foo( [a, b, c] ) {
console.log(a, b, c)
}
foo( 1, 2, 3 );
當我運行這個時,我收到以下錯誤:
Uncaught TypeError: undefined is not a function
現在,我並沒有質疑這個事實並沒有像人們預期的那樣輸出1, 2, 3
因為只有第一個值1
實際上被破壞了( a = 1[0], b = 1[1], c = 1[2]
)。
但事情就是這樣:
我可以完美地寫出1[0], 1[1], 1[2]
並且每個都undefined
。
那么為什么我上面寫的foo
函數拋出一個異常而不是像我期望的那樣簡單地返回3次undefined
。
實際上,如果我按照以下方式編寫bar
,我將會發生3 undefined
情況。
function bar() {
console.log( 1[0], 1[1], 1[2] )
}
bar();
// undefined undefined undefined
有人能告訴我JS在第一個foo()
做了什么以及為什么輸出沒有undefined undefined undefined
?
使用數組模式進行的解構使用后台迭代,即被解構的值必須是可迭代的。
實際上,在Firefox中,錯誤消息似乎更具說明性:
TypeError :(析構參數)不可迭代
這是你在評估1[0], 1[1], 1[2]
時所做的比較出錯的地方:不需要1
可迭代。
更正確的比較是這樣做:
console.log([...1]); // or: const [a, b, c] = 1;
......而且代碼會失敗。
數組解構實際上是迭代器解構,適用於任何實現Symbol.iterator
方法的東西。
例如
function foo([a, b, c]) { console.log([a, b, c]) } foo({ * [Symbol.iterator]() { yield 1; yield 2; yield 3; } })
Number
不實現迭代器協議
console.log(1[Symbol.iterator])
這就是你得到錯誤的原因。
但是如果你實現它( 不推薦 )
Number.prototype[Symbol.iterator] = function*() { yield * this.toString(2); // just an example } function foo([a, b,c]) { console.log(a, b, c); } foo(6)
函數foo()
與bar()
完全不同,因為1
是javascript中的有效數字,並且嘗試訪問1[0]
是undefined
因為它查找值為1
的索引0
,這肯定是undefined
。 這就是為什么你得到三個undefined
的1[0], 1[1], 1[2]
現在,來自foo()
的單個undefined
不是來自console.log()
而是來自錯誤
未捕獲的TypeError:undefined不是函數
由於您的功能簽名不正確。 要以正確的方式使用它,您可以使用擴展語法:
function foo(...arg) { console.log(arg[0], arg[1], arg[2]); } foo( 1, 2, 3 );
這是因為函數foo()
只能接受iterables
。 請參閱以下給出的示例:
function foo( [a, b, c] ) { console.log(a, b, c) } foo( [4, 5, 6] ); // works okay foo( 3,4,5 ); // undefined is not a function
恕我直言, spread operator
在這些類型的場景中用作收集器,如下所示:
function foo( ...[a, b, c] ) { console.log(a, b, c) } foo( ...[4, 5, 'v'] ); //works fine foo(1,3,4); // also works fine
為什么foo()會拋出異常?
那是因為不兼容的參數(b / w caller&calee)與JavaScript 1[0]
undefined
的事實無關。
這是因為函數foo
期望一個數組/字符串,所以他可以破壞它。
由於你沒有傳遞任何東西,導致破壞失敗,這就像做
var arrayVariable = undefined
var [a, b, c] = arrayVariable // this will throw an error
var d = arrayVariable['a'] // this will throw an error
因此,為避免拋出錯誤,請提供數組參數
foo('') // undefined, undefined, undefined
foo('123') // 1, 2, 3
foo([]); // undefined, undefined, undefined
foo([1, 2, 3]) // 1, 2, 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.